最有效和兼容的方式来实现停靠页脚

问题描述 投票:2回答:2

我试图在CSS模板中执行以下操作:

  1. 当没有足够的内容填充页面时,将页脚停靠在底部
  2. 在整个宽度上拉伸页眉和页脚背景
  3. 将所有内容放在页面中间

这是我的代码,在这里帮助创建:http://tinkerbin.com/lCNs7Upq

我的问题是,我已经看到了实现这一目标的几种方法。这是最好的吗?拥有空的div也似乎很遗憾,这是一个小屋吗?

html css sticky-footer
2个回答
6
投票

您可以使用CSS修复和元素到页脚:

position: fixed;
bottom: 0;

但是,我正在试图弄清楚你想要做什么。

如果页面和页脚是div,则页眉和页脚应自动在页面上100%显示。

您的中间部分可以设置为height:auto;通过css并将填充视口将页脚一直推到底部,但要做到这一点,你还必须将主体设置为100%以使其工作。

html, body, #content {
    height: 100%;
    min-height: 100%;
}
#header {
    height: 100px;
    width: 100%;
    background: blue;
    position: fixed;
    top: 0;
}
#content {
    height: auto;
    margin: 100px auto;
    background: green;
}
#footer {
    position: fixed;
    bottom: 0;
    height: 100px;
    width: 100%;
    background: red;
}

您的HTML应该看起来像这样:

<div id="header"></div>
<div id="content"></div>
<div id="footer"></div>

工作示例:http://jsfiddle.net/s4rT3/1/


3
投票

这是我见过的最好的例子:

http://css-tricks.com/snippets/css/sticky-footer/

* {
  margin: 0;
}
html, body {
  height: 100%;
}
.page-wrap {
  min-height: 100%;
  /* equal to footer height */
  margin-bottom: -142px; 
}
.page-wrap:after {
  content: "";
  display: block;
}
.site-footer, .page-wrap:after {
  height: 142px; 
}
.site-footer {
  background: orange;
}
<div class="page-wrap">
  
  Content!
      
</div>

<footer class="site-footer">
  I'm the Sticky Footer.
</footer>

更新:在2019年使用flex是一个更好的选择。

© www.soinside.com 2019 - 2024. All rights reserved.