抱歉,我无法让它工作。应该是一个快速答案。
我的 html 布局如下:
<html>
<header>
...
</header>
<body>
<div class = "background"></div>
<div class = "content">
...
</div>
<body>
</html>
我希望背景 div 仅在页面的整个长度上放置 1000 像素的背景颜色。然后,在该背景颜色内,内容每侧填充 40 像素。
CSS 是这样的:
body {
width:1000px;
margin-left:auto;
margin-right:auto;
}
.background {
position:absolute;
top:0px;
width:1000px;
height:100%;
}
.content {
min-height:100%;
padding-left:40px;
padding-right:40px;
}
我认为它是这样工作的... body div 将扩展以容纳 .content div 的最小高度。这意味着 .background div 的 100% 高度将填充整个正文以及页面的长度。然而事实并非如此。它仅填充窗口高度。我哪里出错了?
谢谢
最佳答案
正如 topek 所猜测的,这样就可以了:
html, body{
height:100%
}
这样做的原因是,百分比 CSS 高度仅在父元素定义了高度时才起作用。通过添加上述内容,您可以为 .background
的 parent 提供高度。
更新:根据OP的评论,以下是如何让.background
div始终显示填充视口(viewport):
html, body {
height: 100%;
padding: 0;
margin: 0;
}
/* Fixed element that takes up entire viewport */
.background {
position: fixed;
z-index: 1;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
/* Content that stacks above .background */
.content {
position: relative;
z-index: 2;
}
随着 .content
变得大于视口(viewport)并且用户滚动,.background
的固定位置将使其始终处于 View 中。
当然,a handy example .
关于html - 另一个CSS 100%高度问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7574756/