网站应始终填满整个屏幕

时间:2013-12-18 17:18:38

标签: html css footer

假设我在网站上有三个盒子(div)(见下图):

  • 带徽标的标题
  • 内容包含一些文字
  • 页脚与联系信息

每个盒子都有独特的颜色(按顺序:黄色,橙色和蓝色)和黑色边框。 我想网站总是填满整个屏幕,徽标位于顶部,页脚位于底部。因此,如果内容中没有足够的文本,则应该扩展内容,以便页脚位于底部。如果内容中有大量文本,则滑块应显示在右侧。

CSS中如何做到这一点?重要的是盒子有背景。我找到了很多解决方案,但没有一个解决方案不适用于背景。

example

2 个答案:

答案 0 :(得分:2)

解决方案

  • 图表中的黑框获得最小高度100%,是滚动容器,位置相对,以允许子位置与其相对。
  • 图表中的红色框实际上由2个框组成:
    • 一个用于动态大小的内容;这有足够的顶部和底部填充为您的页眉和页脚腾出空间,并强制滚动容器展开
    • 一个用于背景;这是绝对位置,相对于黑盒子,其父级指定了顶部和底部位置。
  • 图表中的黄色和蓝色框分别为position: absolutetop: 0bottom: 0 ......或者您选择定位它们。

这是一个小提琴:http://jsfiddle.net/syndicatedshannon/F5c6T/

here是另一个带有显式视口元素的版本,只是为了澄清,匹配颜色和添加的边框来复制OP图形(尽管按照OP,黑色边框实际上是窗口)。

示例HTML

<html>
    <body>
        <div class="background"></div>
        <div class="content"></div>
        <div class="header"></div>
        <div class="footer"></div>
    </body>
</html>

示例CSS

html { position: absolute; height: 100%; left: 10px; right: 10px; overflow: auto; margin: 0; padding: 0; }
body { position: relative; width: 100%; min-height: 100%; margin: 0; padding: 0; }
.background { position: absolute; top: 120px; bottom: 120px; background-color: red; width: 100%; }
.content { position: relative; padding: 120px 0; }
.header { position: absolute; top: 10px; height: 100px; width: 100%; background-color: yellow; }
.footer { position: absolute; bottom: 10px; height: 100px; width: 100%; background-color: cyan; }

另请注意,这假设您还不能依赖CSS3。

答案 1 :(得分:0)

如果您只定位现代浏览器,则可以使用calc()

body, html {
    height: 100%;
    padding: 0;
    margin: 0;
}

.header {
    height: 50px;
    margin-bottom: 10px;
}

.footer {
    height: 100px;
    margin-top: 20px;
}

.content {
     min-height: calc(100% - 50px - 10px - 100px - 20px);
}

缺点是您需要知道页眉和页脚大小,并且需要修复它们。如果不使用Javascript,我不知道如何解决这个问题。对于稍微不那么现代的浏览器,您可以使用border-box来获得与上面相同的效果。

body, html {
    height: 100%;
    padding: 0;
    margin: 0;
}

.header {
    height: 50px;
    margin-bottom: 10px;
    z-index: 5;
    position: relative;
}

.footer {
    height: 100px;
    margin-top: -100px;
    z-index: 5;
    position: relative;
}

.content {
    box-sizing: border-box;
    padding: 60px 0 120px 0;
    margin-top: -60px;
    min-height: 100%;
    z-index: 1;
    position: relative;
}

最后,这是JS解决方案:

$(function(){
    $('.content').css('min-height',
            $(window).height()
            - $('.header').outerHeight()
            - $('.footer').outerHeight() - $('.content').marginTop()
            - $('.content').marginBottom());
});

编辑:我的JS解决方案采用边框并且没有边框。这个解决方案应该更加强大:

function setContentSize() {
    $('.content').css('min-height',
            $(window).height()
            - $('.header').outerHeight()
            - $('.footer').outerHeight()
            - ($('.content').outerHeight()
                - $('.content').innerHeight()));
}

$(setContentSize);
$(window).on('resize', setContentSize);
相关问题