有问题的网页如下所示:
// The Header //
/* */
/* CONTENT */
/* */
// The footer //
页眉和页脚都有固定的高度。让我们说例如两者的高度都是20px。我需要将内容的高度设置为100%减去40px(页眉+页脚高度)。我知道我可以使用JavaScript轻松完成这项工作,但如果有可能的话,学习如何使用纯CSS来实现它会很酷。
答案 0 :(得分:25)
如果您的浏览器支持CSS3,请尝试使用CSS元素Calc()
height: calc(100% - 65px);
您可能还想添加浏览器兼容性选项:
height: -o-calc(100% - 65px); /* opera */
height: -webkit-calc(100% - 65px); /* google, safari */
height: -moz-calc(100% - 65px); /* firefox */
答案 1 :(得分:9)
#header /* hypothetical name */
{
height:100%;
}
#header p /* or any other tag */
{
margin:20px 0 20px 0;
}
请确保不要在同一标签中放置边距和高度。你会遇到一些疯狂的结果。
答案 2 :(得分:3)
在页眉和页脚上放置一个固定位置,并将它们分别固定在窗口底部的顶部。然后在内容区域20px上放置一个顶部和底部填充。
#header{position:fixed;top:0}
#footer{position:fixed;bottom:0}
#content{padding:20px 0}
答案 3 :(得分:3)
Marnix的答案涉及使用内容元素的顶部和底部填充;我的涉及使用顶部和底部边界。
我自己偶然发现了这个解决方案,同时试图弄清楚如何做一些类似的而不用求助于表格:将中心元素的高度设为100%,然后将框尺寸模型设置为“border-box”(使得高度不仅包括盒子内的内容,还包括盒子周围的边框),使顶部和底部边框非常厚(比如20px),然后使用固定定位覆盖页眉和页脚在中央元素的疯狂厚的顶部和底部边界上。
以下是我的示例CSS:
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#content {
height: 100%;
-moz-box-sizing: border-box;
box-sizing: border-box;
/* Ensure that the height of the element includes the
box border, not just the content */
border: 0;
border-top: 20px solid white;
border-bottom: 20px solid white;
/* Leave some space for the header and footer to
overlay. */
}
#header,
#footer {
position: fixed;
left: 0;
right: 0;
height: 20px;
background-color: #eee;
/* Specify a background color so the content text doesn't
bleed through the footer! */
}
#header {
top: 0;
}
#footer {
bottom: 0;
}
这适用于Google Chrome 24 for Mac。不过,我没有在其他浏览器中尝试过它。
希望这会帮助那些仍然面临诱惑的人只使用一张桌子并完成页面布局。 : - )
答案 4 :(得分:0)
此示例似乎显示了执行此操作的最强大方法。实际上,它在IE中有点儿麻烦,因为有时候调整大小会出错。 也就是说,当从右下角进行调整大小并且只是手动执行垂直调整大小时(有时很难做到),页面将不会在IE中刷新。我遇到了同样的问题,毕竟用JS修复了它,因为我的网页上有其他事件。