绝对定位页脚的正确方法

时间:2014-04-29 09:22:20

标签: css position

我使用

将页脚放在页面底部
position:absolute;
bottom:0;

但是对于太“低”的页面(height的{​​{1}}很小),页脚和窗口底部之间有空间。我通过为html元素设置min-height来修复它,我认为这是一个难看的解决方案。一个百分比在这里不起作用。理想情况下,html的{​​{1}}应该是我猜的窗口高度。我可以用Javascript修复它,但这看起来也太复杂了。

所以我删除min-height将页脚完全放在窗口上,但对于“高”页面来说甚至更糟糕。有关效果,请参阅this fiddle

是否有更优雅的替代方案? 想要使用html因为这会导致页脚成为总是可见的,在大多数情况下,我发现浪费了窗户空间。如果有人有任何建议,请随时编辑小提琴。

3 个答案:

答案 0 :(得分:2)

感谢您的建议,他们让我走上正轨。我认为诀窍是

html{
    height:100%;
}

body{
    position:relative;
    min-height:100%;
}

这实现了没有非语义.wrapper div's 的预期效果。有关演示,请参阅here

在某些情况下,在页脚之前的元素上需要一些padding-bottom,以免被页脚遮挡。

<强>更新

我想我找到了final solution

body{
margin-bottom:50px;
}

结合

.footer{
position:absolute;
bottom:-50px;
}

将使用干净的CSS和语义标记为页脚之前的所有内容创建空间和边距。

答案 1 :(得分:0)

ul列表与父div包裹在一起,并使其高度为:100%;

并且标题不需要top:0

.footer{
  bottom:0;
  position:absolute;
}

<强> Updated DEMO

答案 2 :(得分:0)

您需要在底部布局中使用页脚。试试我的示例代码

<强> HTML

<body>
    <div id="wrapper">
        <div class="w1">
            <p>content of the page</p>
            <p>content of the page</p>
            <p>content of the page</p>
            <p>content of the page last</p>
        </div>
    </div>
    <div id="footer">footer content</div>
</body>

<强> CSS

html,
body{
    height:100%;
    margin:0;
}
#wrapper{
    background:#000;
    min-height:100%;
    width:100%;
    margin:0 auto;
}
.w1{
    background:#f00;
    padding-bottom:50px; /* footer height */
}
#footer{
    background:#ff0;
    position:relative;
    width:100%;
    height:50px;
    margin-top:-50px; /* footer height */
}