繁体   English   中英

CSS - 100%的高度减去#px - 页眉和页脚

[英]CSS - Height of 100% minus #px - Header and Footer

有问题的网页如下所示:

// The Header //
/*            */
/*  CONTENT   */
/*            */
// The footer //

页眉和页脚都有固定的高度。 让我们说例如两者的高度都是20px。 我需要将内容的高度设置为100%减去40px(页眉+页脚高度)。 我知道我可以使用JavaScript轻松完成这项工作,但如果有可能的话,学习如何使用纯CSS来实现它会很酷。

如果您的浏览器支持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 */
#header /* hypothetical name */
{
    height:100%;
}

#header p /* or any other tag */
{
    margin:20px 0 20px 0;
}

只需确保不在同一标签中放置边距和高度。 你会遇到一些疯狂的结果。

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。 不过,我还没有在其他浏览器中尝试过。

希望这会帮助那些仍然面临诱惑的人只使用表格并完成页面布局。 :-)

在页眉和页脚上放置一个固定位置,并将它们分别固定在窗口底部的顶部。 然后在内容区域20px上放置一个顶部和底部填充。

#header{position:fixed;top:0}
#footer{position:fixed;bottom:0}
#content{padding:20px 0}

这个例子似乎表明了最强大的方法。 实际上,它在IE中有点儿麻烦,因为有时候调整大小会出错。 也就是说,当从右下角进行调整大小并且只是手动执行垂直调整大小时(有时很难做到),页面将不会在IE中刷新。 我有同样的问题,毕竟用JS修复它,因为我的网页上有其他事件。

http://www.xs4all.nl/~peterned/examples/csslayout1.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM