我有一个简单的2列布局,带有一个脚注,可以清除标记中的左右div。我的问题是,我不能让页脚留在所有浏览器的页面底部。如果内容向下推页脚,它就会起作用,但情况并不总是如此。


当前回答

对于自然的页眉和页脚高度使用CSS Flexbox。

参见JS Fiddle。

HTML

<body>
  <header>
    ...
  </header>
  <main>
    ...
  </main>
  <footer>
    ...
  </footer>
</body>  

CSS

html {
  height: 100%;
}

body {
  height: 100%;
  min-height: 100vh;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;
  margin: 0;
  display: flex;
  flex-direction: column;
}

main {
  flex-grow: 1;
  flex-shrink: 0;
}

header,
footer {
  flex: none;
}

其他回答

设置#页脚的CSS为:

position: absolute;
bottom: 0;

然后,您需要在#边栏和#内容的底部添加填充或边距,以匹配#footer的高度,或者当它们重叠时,#footer将覆盖它们。

此外,如果我没记错的话,IE6在底部有一个问题:0 CSS。你可能不得不为IE6使用JS解决方案(如果你关心IE6的话)。

在我的网站上,我总是使用:

position: fixed;

...在我的CSS页脚。将它固定在页面底部。

对于这个问题,我看到的许多答案都是笨拙的,难以实现和低效的,所以我想我应该尝试一下,并提出我自己的解决方案,只是一点点css和html

超文本标记语言 身体{ 高度:100%; 保证金:0; } .body { Min-height: calc(100% - 2rem); 宽度:100%; 背景颜色:灰色; } .footer { 高度:2快速眼动; 宽度:100%; 背景颜色:黄色; } 身体< > <div class="body">test as body</div> <div class="footer">test as footer</div> 身体< / >

这是通过设置页脚的高度,然后使用CSS计算出页面的最小高度,页脚仍然在底部,希望这有助于一些人:)

要获得一个粘性页脚:

为你的内容设置一个<div> with class="wrapper"。 在包装器的</div>结束之前放置 < div class = "推" > < / div >。 在包装器的</div>结束后放置 < div class = "脚注" > < / div >。

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

我创建了一个非常简单的库https://github.com/ravinderpayal/FooterJS

它使用起来很简单。在包含库之后,只需调用这行代码。

footer.init(document.getElementById("ID_OF_ELEMENT_CONTAINING_FOOTER"));

页脚可以通过使用不同的参数/id调用上面的函数来动态更改。

footer.init(document.getElementById("ID_OF_ANOTHER_ELEMENT_CONTAINING_FOOTER"));

注意:-你不必改变或添加任何CSS。库是动态的,这意味着即使屏幕在加载页面后调整大小,它也会重置页脚的位置。我创建了这个库,因为CSS解决了这个问题,但当显示的大小发生显著变化时,从台式机到平板电脑或反之亦然,它们要么重叠的内容,要么不再保持粘性。

另一种解决方案是CSS媒体查询,但你必须为不同大小的屏幕手动编写不同的CSS样式,而这个库自动工作,并由所有基本的JavaScript支持浏览器支持。

编辑 CSS解决方案:

@media only screen and (min-height: 768px) {/* or height/length of body content including footer*/
    /* For mobile phones: */
    #footer {
        width: 100%;
        position:fixed;
        bottom:0;
    }
}

现在,如果显示的高度超过你的内容长度,我们将使页脚固定在底部,如果不是,它将自动出现在显示的最后,因为你需要滚动来查看它。

而且,它似乎是一个比JavaScript/库更好的解决方案。