以下代码works properly
<!DOCTYPE html>
<html>
<head>
<title>Working</title>
<style type="text/css">
html {
height: 100%;
}
body {
height: 100%; /* !!!!! difference in here */
}
div#main {
min-height: 100%;
background-color: red;
}
</style>
</head>
<body>
<div id="main"></div>
</body>
当代码使用 min-height
而不是 height
作为正文时 prevents #main from occupying space
<!DOCTYPE html>
<html>
<head>
<title>Not working</title>
<style type="text/css">
html {
height: 100%;
}
body {
min-height: 100%; /* !!!!! difference in here */
}
div#main {
min-height: 100%;
background-color: red;
}
</style>
</head>
<body>
<div id="main"></div>
</body>
奇怪的是,在 chrome 中进行检查时,在这两种情况下,正文都会正确占用 100% 的空间。然而,在 min-height
情况下,子元素 min-height: 100%;
转换为 0。为什么会发生这种情况,是否有任何解决方法?我希望我的网页背景的最小高度能够正常工作并根据需要扩展。
最佳答案
关于“为什么会这样?”
min-height
属性仅在设置了显式高度时才有效。 The spec读取百分比:
Specifies a percentage for determining the used value. The percentage is calculated with respect to the height of the generated box's containing block. If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the percentage value is treated as '0' (for 'min-height') or 'none' (for 'max-height').
其中的关键点是“如果包含 block 的高度不是
明确指定(即,它取决于内容高度)。”当 body
设置为 min-height
时,它仍然取决于内容高度对于计算,只有它不允许它低于指定大小(在您的情况下,html
高度的 100% 已明确设置)。但是,因为 body
是仍然根据内容来设置其高度,然后 div#main
无法计算 min-height
因为 body
没有明确的高度设置。
是否需要“解决方法”?
似乎将 body
设置为 height: 100%
就可以实现所有你想要的。是否content is long或 content is short .
对 html
更改 background-color
的评论的回应
我怀疑原因your fiddle使用 html
和 background-color
设置改变是因为 this spec 中的符号(引述如下)。通过在 html
上设置它会更改 canvas 渲染自身:
The background of the root element becomes the background of the canvas and covers the entire canvas, anchored (for 'background-position') at the same point as it would be if it was painted only for the root element itself. The root element does not paint this background again.
For HTML documents, however, we recommend that authors specify the background for the BODY element rather than the HTML element. For documents whose root element is an HTML "HTML" element or an XHTML "html" element that has computed values of 'transparent' for 'background-color' and 'none' for 'background-image', user agents must instead use the computed value of the background properties from that element's first HTML "BODY" element or XHTML "body" element child when painting backgrounds for the canvas, and must not paint a background for that child element. Such backgrounds must also be anchored at the same point as they would be if they were painted only for the root element.
关于html - 当 body 的最小高度为 100% 时, body 的子元素不占用 100% 的空间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10686084/