使页脚正确地固定在页面底部

238

我试图让我的页脚(只是一个带有一行文本的div)在内容没有占满整个屏幕时位于屏幕底部,或在需要滚动条的情况下位于内容底部。如果内容不需要滚动条,它能正常工作,但当内容太长时,页脚仍然在同一位置,紧贴内容。

我的基本div结构如下:

<div id="container">
    <div id="body"></div>
    <div id="footer"></div>
</div>

我相应的 CSS(略微简化):

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

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

#container {
    width: 674px;
    min-height: 100%;
    height: 100%;
    position: relative;
    margin: 0 auto;
}

#body {
    width: 616px;
    padding: 5px 14px 5px 14px;
    margin: 0 auto;
    padding-bottom: 20px;
}

#footer {
    position: absolute;
    bottom: 0;
    width: 644px;
    height: 20px;
    margin: 0 auto;
}

2
这个问题在提供的链接中没有可靠的答案。接受的答案应该是由Vinicius José Latorre在这个问题中提供的,因为它非常清晰并且有效。 - Exel Gamboa
也许问题出在HTML或BODY标签上。这个链接对我很有帮助:https://makandracards.com/makandra/39473-stretching-an-html-page-to-full-height - sina
10个回答

247

最简单的解决方法是在 <html> 标签上使用 min-height,并使用 position:absolute; 定位 <footer>

示例: jsfiddle 和 SO 代码片段:

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

body {
    margin: 0 0 100px;
    /* bottom = footer height */
    padding: 25px;
}

footer {
    background-color: orange;
    position: absolute;
    left: 0;
    bottom: 0;
    height: 100px;
    width: 100%;
    overflow: hidden;
}
<article>
    <!-- or <div class="container">, etc. -->
    <h1>James Dean CSS Sticky Footer</h1>
    <p>Blah blah blah blah</p>
    <p>More blah blah blah</p>
</article>
<footer>
    <h1>Footer Content</h1>
</footer>


6
我也喜欢它 - 谢谢。不过,一个问题:为什么要使用“overflow: hidden;”? - daOnlyBG
2
这是一个相当不错的解决方案。唯一的缺点是页脚高度的绝对定位... :/。尽管如此,我仍然使用了您的解决方案 :) - simon
1
供日后参考:一开始这个对我不起作用,因为我明确设置了 html { height: 100%; } - Niek
2
这个回答很好,但是抄袭别人的代码,一行一行地抄,甚至不给出任何引用,这样做太不酷了。因为这个原因我给负一分。http://mystrd.at/modern-clean-css-sticky-footer/ - Greeso
4
在短页面上设置页脚的绝对位置很糟糕,因为它会覆盖其他静态元素。 - clusterBuddy
显示剩余8条评论

27

为什么不使用:{ position: fixed; bottom: 0 }


144
由于页脚会遮挡您的正文内容。 - cope360
30
-1 是因为这样你的页脚会随着页面滚动而移动。 - Shalom Sam
position: static 怎么样?这对我来说效果更好! - Zain Shaikh
8
“position: static” 是所有元素的默认定位方式,设置此属性不会使内容高度不足时将页脚固定在视口底部。 - simmer
我认为 {position: absolute; bottom:0} 应该可以。 - Solomon Sunday

19

我使用的一个简单解决方案,适用于IE8+。

在html上使用min-height:100%,这样即使内容较少,页面仍会占据整个视口高度,页脚会固定在页面底部。当内容增加时,页脚会随内容向下移动并保持固定在底部。

JS fiddle工作演示:http://jsfiddle.net/3L3h64qo/2/

Css

html{
  position:relative; 
  min-height: 100%;
}
/*Normalize html and body elements,this style is just good to have*/
html,body{
  margin:0;
  padding:0;
}
.pageContentWrapper{
  margin-bottom:100px;/* Height of footer*/
} 
.footer{
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height:100px;
    background:#ccc;
}

Html

   <html>
    <body>
        <div class="pageContentWrapper">
            <!-- All the page content goes here-->
        </div>
        <div class="footer">
        </div>
    </body>
    </html>

5
请使用这个。它会修复它。
#ibox_footer {
    padding-top: 3px; 
    position: absolute;
    height: 20px;
    margin-bottom: 0;
    bottom: 0;
    width: 100%;
}

4
如果包含元素在屏幕底部之前结束,那么它就不会显示出来。 - YakovL

4

使用一个像素值作为最小高度,而不是 %
例如:

min-height:620px;
height:auto;

并且页脚如下:
.footer {
    height:70px;
    clear:both;
    position:relative;
    bottom:0;
    width: 100%;
}

2

使用jQuery,将代码放在<head></head>标签中即可

<script type="text/javascript">
$(document).ready(function() { 
    var docHeight = $(window).height();
    var footerHeight = $('#footer').height();
    var footerTop = $('#footer').position().top + footerHeight;  
    if (footerTop < docHeight) {
        $('#footer').css('margin-top', 10 + (docHeight - footerTop) + 'px');
    }
});
</script>

5
很难快速管理和理解,更整洁的选择是纯 CSS 实现。 - landed
不久之前,我也在做类似的事情,但页脚的高度是根据浏览器或甚至页面刷新而有所不同。看起来很奇怪。虽然它有点起作用,但我建议不要使用这种方法。我当时是检索outerHeight。 - Kitet
@landed 纯CSS解决方案的问题在于要么是“固定高度”,要么是“固定高度和溢出隐藏”。任何使用CMS的人都会遇到困难,而在响应式设计时代,固定高度已经不再流行。 - Eoin
2
@eoin 我同意你的观点,固定高度出于这些原因并不是很好。但在完美的世界(或后续的CSS规范)中,我更喜欢纯CSS解决方案。理想情况下,我希望看到JS不创建任何样式或布局。 - landed
当然,这不是一个完美的世界,但它正在变得更好。即使在::after中使用HTML也不是可行的解决方案(并且永远不会成为可行的解决方案)。 - Eoin

2

这应该能帮助到你。

* {
    margin: 0;
}
html, body {
    height: 100%;
}
.wrapper {
    min-height: 100%;
    height: auto !important;
    height: 100%;
    margin: 0 auto -155px; /* the bottom margin is the negative value of the footer's height */
}
.footer {
    height: 155px;
}

1
这里分享的模型与Ryan Fait的StickyFooter非常相似http://ryanfait.com/sticky-footer。到目前为止,这个讨论中只有一个div缺失(Kenneth Palanganas在此提出的模型在Win81本地设计中运作良好约48小时,然后在ie/chrome中因未知原因崩溃)。Ryan的“push” div将满足一些不情愿的浏览器。请注意,px是通常的单位,但为了液态布局的一致性,可能更喜欢使用em。
* { border: 0; margin: 0; padding: 0; }
html, body { height: 100%; }
.wrapper { height: auto !important; height: 100%; margin: 0 auto -1em; min-height: 100%; }
.footer, .push { height: 1em; }

<div class="wrapper"><p>Your website content here.</p>
<div class="push"></div>
</div>
<div class="footer"><p>This is a footer</p>
</div>

1
最简单的方法是将页面容器的min-height设置为400px,假设您的页脚在最后。您甚至不需要为页脚放置CSS,或者只需将width:100%应用于您的页脚,假设它是<body>的直接子元素。

1
我想分享一下我是如何使用Javascript函数解决这个问题的,该函数在页面加载时调用。当页面内容的高度小于屏幕高度时,此解决方案将页脚定位在屏幕底部。请保留HTML标签。

function fix_layout(){
  //increase content div length by uncommenting below line
  //expandContent();
  
    var wraph = document.getElementById('wrapper').offsetHeight;
    if(wraph<window.innerHeight){ //if content is less than screenheight
        var headh   = document.getElementById('header').offsetHeight;
        var conth   = document.getElementById('content').offsetHeight;
        var footh   = document.getElementById('footer').offsetHeight;
        //var foottop = window.innerHeight - (headh + conth + footh);
        var foottop = window.innerHeight - (footh);
        $("#footer").css({top:foottop+'px'});
    }
}

function expandContent(){
  $('#content').append('<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed at ante. Mauris eleifend, quam a vulputate dictum, massa quam dapibus leo, eget vulputate orci purus ut lorem. In fringilla mi in ligula. Pellentesque aliquam quam vel dolor. Nunc adipiscing. Sed quam odio, tempus ac, aliquam molestie, varius ac, tellus. Vestibulum ut nulla aliquam risus rutrum interdum. Pellentesque lorem. Curabitur sit amet erat quis risus feugiat viverra. Pellentesque augue justo, sagittis et, lacinia at, venenatis non, arcu. Nunc nec libero. In cursus dictum risus. Etiam tristique nisl a nulla. Ut a orci. Curabitur dolor nunc, egestas at, accumsan at, malesuada nec, magna.</p>'+

'<p>Nulla facilisi. Nunc volutpat. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Ut sit amet orci vel mauris blandit vehicula. Nullam quis enim. Integer dignissim viverra velit. Curabitur in odio. In hac habitasse platea dictumst. Ut consequat, tellus eu volutpat varius, justo orci elementum dolor, sed imperdiet nulla tellus ut diam. Vestibulum ipsum ante, malesuada quis, tempus ac, placerat sit amet, elit.</p>'+

'<p>Sed eget turpis a pede tempor malesuada. Vivamus quis mi at leo pulvinar hendrerit. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Pellentesque aliquet lacus vitae pede. Nullam mollis dolor ac nisi. Phasellus sit amet urna. Praesent pellentesque sapien sed lacus. Donec lacinia odio in odio. In sit amet elit. Maecenas gravida interdum urna. Integer pretium, arcu vitae imperdiet facilisis, elit tellus tempor nisi, vel feugiat ante velit sit amet mauris. Vivamus arcu. Integer pharetra magna ac lacus. Aliquam vitae sapien in nibh vehicula auctor. Suspendisse leo mauris, pulvinar sed, tempor et, consequat ac, lacus. Proin velit. Nulla semper lobortis mauris. Duis urna erat, ornare et, imperdiet eu, suscipit sit amet, massa. Nulla nulla nisi, pellentesque at, egestas quis, fringilla eu, diam.</p>'+

'<p>Donec semper, sem nec tristique tempus, justo neque commodo nisl, ut gravida sem tellus suscipit nunc. Aliquam erat volutpat. Ut tincidunt pretium elit. Aliquam pulvinar. Nulla cursus. Suspendisse potenti. Etiam condimentum hendrerit felis. Duis iaculis aliquam enim. Donec dignissim augue vitae orci. Curabitur luctus felis a metus. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. In varius neque at enim. Suspendisse massa nulla, viverra in, bibendum vitae, tempor quis, lorem.</p>'+

'<p>Donec dapibus orci sit amet elit. Maecenas rutrum ultrices lectus. Aliquam suscipit, lacus a iaculis adipiscing, eros orci pellentesque nisl, non pharetra dolor urna nec dolor. Integer cursus dolor vel magna. Integer ultrices feugiat sem. Proin nec nibh. Duis eu dui quis nunc sagittis lobortis. Fusce pharetra, enim ut sodales luctus, lectus arcu rhoncus purus, in fringilla augue elit vel lacus. In hac habitasse platea dictumst. Aliquam erat volutpat. Fusce iaculis elit id tellus. Ut accumsan malesuada turpis. Suspendisse potenti. Vestibulum lacus augue, lobortis mattis, laoreet in, varius at, nisi. Nunc gravida. Phasellus faucibus. In hac habitasse platea dictumst. Integer tempor lacus eget lectus. Praesent fringilla augue fringilla dui.</p>');
}
/*sample CSS*/
body{ background: black; margin: 0; }
#header{ background: grey; }
#content{background: yellow; }
#footer{ background: red; position: absolute; }

#header, #content, #footer{ display: inline-block; width: 100vw; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body onload="fix_layout()">
        <div id="wrapper">
            <div id="header" class="navbar navbar-inverse navbar-fixed-top" role="navigation">
                [some header elements here]
            </div>
            <div id="content" class="container">
              [some content elements here]
              
              
            </div>
            <div id="footer" class="footer">
                [some footer elements here]
            </div>
        </div>
    </body>

希望这有所帮助。

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