您的位置:首页 > Web前端 > CSS

CSS百分比定义高度

2015-08-31 10:51 621 查看
css中,百分比的高度在设定时需要根据这个元素的父元素容器的高度。所以,如果你把一个div的高度设定为height:
50%;,而它的父元素的高度是100px,那么,这个div的高度应该是50px。

Web浏览器在计算有效高度时,浏览器根本就不计算内容的高度,除非内容超出了视窗范围(导致滚动条出现)。或者你给整个页面设置一个绝对高度。否则,浏览器就会简单的让内容往下堆砌,页面的高度根本就无需考虑。

因为页面并没有缺省的高度值,所以,当你让一个元素的高度设定为百分比高度时,无法根据获取父元素的高度,也就无法计算自己的高度。换句话说,父元素的高度只是一个缺省值:height:
auto;。当你要求浏览器根据这样一个缺省值来计算百分比高度时,只能得到undefined的结果。也就是一个null值,浏览器不会对这个值有任何的反应。

例如

<style type="text/css">
body {}{
margin: 0;
padding: 0;
border: 0;
background-color: #EFECE6;
}
#content {}{
width: 958px;
height: 100%;
border-left: solid 1px #c00;
border-right: solid 1px #c00;
background-color: #fff;
margin: 0 auto;
padding: 0 1em 0 1em;
font: 12px/1.5 Verdana;
}
#content h1 {}{
color: #3e3e3e;
font: 22px/1.2 Georgia;
margin: 0;
padding: 0;
}
#content h2 {}{
color: #4d4a42;
font: 14px/1.3 Verdana;
margin: 0;
padding: 0;
}
</style>
<body>
<div id="content">
<h1>Height 100%―Not Working</h1>
<h2>Example</h2>
<p id="by">
</p>
<p>
The CSS <code>height</code> property can be frustrating to use, because, especially if you are setting heights as a percentage of the browser window, they don't always work.
</p>
<p>
For example, this page you are on currently has a height set to this main content <code>div</code> of 100%, but as you can see, it is not filling up the entire page. Instead it is filling up only the amount of space that this text takes up.
</p>
<p>
learn how to get your elements to fill up the full height of a browser window.
</p>
</div>
</body>


参考资料: CSS百分比定义高度的问题 http://www.studyofnet.com/news/896.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: