直接上代码吧
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
}
html {
height: 100%;
}
body {
min-height: 100%;
}
#main {
background-color: #333;
color: #eee;
min-height: 100%;
}
</style>
</head>
<body>
<p id="main">
This is main section
</p>
</body>
</html>
https://jsfiddle.net/yaxin/rj7Ljwyx/
上面的代码中,html和body都已经是100%了也就是说body是有高度的,但是为很么#main
元素没有撑开还是一行字体的高度。
当body
设置height
而不是min-height
为100%
时可以实现上述需求,但是为什么?
All the answers above set height: 100%. Didn’t you see the sentence of the question “When the body sets height instead of min-height to 100%, the above requirements can be achieved, but why?”
The question is asking why?
Let me tell you my understanding:
Percentage of 1.height
When we set a percentage height to a block element, we often fail to see the effect.
Because the percentage size is relative to the height of its nearest parent element, that is, its nearest parent element There should be an explicit height value for its percentage height to take effect.
Percentage of 2.min-height
The element with min-height set can be stretched to the height set by min-height even when the height of the content is very small;
When the height of the content is greater than min-height, it is set to the height of the content.
For the percentage value of min-height to take effect, the height value of its parent element must be a fixed height or a valid percentage height.
It is worth noting that when the parent element sets a valid min-height but does not set the height attribute, the height and min-height percentage of the child element will not take effect. Because setting height and min-height must be based on a setting A parent element with a fixed height or a valid percentage height.
This multi-layer percentage height nested style should be avoided as much as possible, because the percentage height of the child element is based on the percentage height of the parent element, and the premise is that the parent element of the parent element must have a clear height.
Supplement:
Not only is the height the same, but the width is also the same.
"CSS Definitive Guide" points out that the height width percentage is relative to the containing block.
"CSS Definitive Guide" also points out (P180) that if the height of the declared containing block is not displayed, the percentage height will be reset to auto, so setting the height of the above html to any value is the same as not setting it.
Set to height, min-height cannot be set
html,body {
The body and html tags are special
and both need to be set
height:100%
to make the height of the sub-elements in the body use percentages.