CSS使两个垂直堆叠的div在一个固定高度时填充视口(viewport)

标签 css layout

我认为这会相当简单,但我一直未能找到解决方案。我想要一个包含 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>

JSFiddle

我见过几种针对粘性页脚的解决方案,但它们似乎都具有重叠的 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);
}

http://jsfiddle.net/9Zhaa/5/

关于CSS使两个垂直堆叠的div在一个固定高度时填充视口(viewport),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18972188/

相关文章:

javascript - 如何计算打印HTML的CSS分页符?

flash - 如何避免过度张贴(重叠)标签?

css - 使用 CSS 的多个等高框边框列——*没有*背景图像?

html - 日期选择器日历顶部的 Jquery slider 按钮

javascript - 单击时如何将特定的 div 滚动到 iframe 的顶部?

css - 将鼠标悬停在 div 上时更改文本颜色

android - 一个ListView支持多少种资源布局?

Android开发最佳实践

缩放变换后的 CSS3 float 位置

javascript - 在屏幕中垂直居中文本