如何将HTML5和CSS3中的<footer>元素固定在页面底部?

20

当我在没有内容的情况下使用position: relative时,页脚上移;当有很多内容时使用position: absolute,页脚下移;当使用position: fixed时,页脚一直存在。

是否有简单的方法使页脚独立于内容出现在页面底部,并随着内容的增减而伸缩?

当页面存在大量内容时,我们可以在第一页看到页脚;而当内容很少时,我们会在底部看到页脚。

<!DOCTYPE html>
<html>
<head>
    <style type="text/css">
        html,body {
            padding: 0;
            margin: 0;
        }

        header {
            position:fixed;
            top:0;
            width:100%;
            height:40px;
            background-color:#333;
            padding:20px;
        }

        footer {
            background-color: #333;
            width: 100%;
            bottom: 0;
            position: relative;
        }
        #main{
            padding-top:100px;
            text-align:center;
        }
  </style>
</head>
<body>
    <header>
    header
    </header>

    <div id="main">
    main
    </div>

    <footer>
    footer
    </footer>
</body>
</html>

这里,我找到了一个很好的例子,但是添加了很多未使用的CSS代码。 http://twitter.github.io/bootstrap/examples/sticky-footer-navbar.html - Joe
将display:inline-block添加到页脚本身,我通常在常见情况下使用它。 - Hendra Nucleo
4个回答

30

将页脚的 position: relative; 改为 position: fixed;

 footer {
            background-color: #333;
            width: 100%;
            bottom: 0;
            position: fixed;
        }

示例:http://jsfiddle.net/a6RBm/


10

这里是一个使用css3的例子:

CSS:

html, body {
    height: 100%;
    margin: 0;
}
#wrap {
    padding: 10px;
    min-height: -webkit-calc(100% - 100px);     /* Chrome */
    min-height: -moz-calc(100% - 100px);     /* Firefox */
    min-height: calc(100% - 100px);     /* native */
}
.footer {
    position: relative;
    clear:both;
}

HTML:

<div id="wrap">
    body content....
</div>
<footer class="footer">
    footer content....
</footer>

jsfiddle

更新:
如@Martin所指出的,.footer元素上的´position:relative´不是必需的,同样适用于clear:both。这些属性只是作为示例而存在。因此,将页脚固定在底部所需的最小CSS应该是:

html, body {
    height: 100%;
    margin: 0;
}
#wrap {
    min-height: -webkit-calc(100% - 100px);     /* Chrome */
    min-height: -moz-calc(100% - 100px);     /* Firefox */
    min-height: calc(100% - 100px);     /* native */
}

此外,在css-tricks上有一篇非常好的文章,展示了不同的方法来实现这一点:https://css-tricks.com/couple-takes-sticky-footer/


你确定在页脚元素上需要使用 position: relative 吗?你的解决方案很好,因为指定了高度。但我认为页脚上不需要使用 position: relative。只有当页脚元素下面有一些带有 position: absolute 的子元素,并且你想将这个子元素相对于页脚放置时,才需要使用它。 - Martin
@Martin,“position: relative”不是必须的,同样适用于“clear: both”和“#wrap”元素上的“padding”。我只是将这些属性作为HTML页面的最小结构示例。感谢您的提醒,我会更新答案。 - Victor

7
我会在HTML 5中使用这个...只是说一下。
#footer {
  position: absolute;
  bottom: 0;
  width: 100%;
  height: 60px;
  background-color: #f5f5f5;
}

7
绝对定位会将一个元素(这里指页脚)从文档流中取出,因此如果您的页面有很多垂直内容,页脚将被放置在这些内容之上。 - Martin

1

只需将页脚元素的 position 属性设置为 fixed(而不是 relative)

Jsbin 示例

请注意,您可能还需要将 main 元素的 margin-bottom 设置为至少等于页脚元素的高度(例如 margin-bottom: 1.5em;),否则在某些情况下,主内容的底部区域可能会被页脚部分重叠。


但是有很多内容,它仍然在jsfiddle.net/84LxZ上。 - Joe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接