我认为这会相当简单,但我一直未能找到解决方案。我想要一个包含 2 个 div 的布局来填充浏览器窗口。它们将是 100% 宽度并且一个在另一个之上。底部 div 必须具有固定高度,顶部 div 将填充其余空间。我想要解决方案:
- 仅使用 CSS(无 Javascript)
- 与 IE7+ 兼容(例如,无 CSS 计算)
- div之间没有重叠
- 如果顶部 div 的内容不适合布局,则垂直滚动它
我尝试了以下方法,但 margin-bottom 似乎没有效果,所以两个 div 重叠(如半透明背景所示):
<!DOCTYPE html>
<html>
<head>
<style>
* {
margin: 0;
padding: 0;
}
body, html {
height: 100%;
}
#content {
height: 100%;
width: 100%;
overflow: auto;
background: rgba(255,0,0,0.5);
margin-bottom: 40px;
}
#footer {
width: 100%;
height: 40px;
position:absolute;
bottom: 0;
background: rgba(255,0,0,0.5);
}
</style>
</head>
<body>
<div id="content">
<p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>content</p><p>last line of content</p>
</div>
<div id="footer"></div>
</body>
</html>
我见过几种针对粘性页脚的解决方案,但它们似乎都具有重叠的 div。这真的像看起来那么难,还是我遗漏了什么?任何见解将不胜感激!
最佳答案
你试过吗?
* {
margin: 0;
padding: 0;
}
body, html {
height: 100%;
}
#content {
width: 100%;
position: absolute;
top: 0;
bottom: 0;
overflow: auto;
background: rgba(255,0,0,0.5);
margin-bottom: 40px;
}
#footer {
width: 100%;
height: 40px;
position: absolute;
bottom: 0;
background: rgba(255,0,0,0.5);
}
关于CSS使两个垂直堆叠的div在一个固定高度时填充视口(viewport),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18972188/