将 div 固定在页面底部

34

所以我制作了一个联系页面,我希望页脚的 div 不会在联系表单之后,而是始终贴着页面底部。

如果我把所有内容都放到一个高度为 100% 的容器 div 中,并将页脚设为 bottom:0;,那么页面就会变得“太长”,必须滚动等等...

我的 css 到目前为止:

#footer{
    background-color:#fff;
    font:bold 14px;
    color:#1E88E5;
    width:100%;
    height:auto;
    padding:1%;
    border-top:1px solid #1E88E5;
}

页脚只是一个普通的全宽 div,目前带有一些居中文本。


您是否希望在不需要滚动的情况下看到页脚? - Donnie D'Amato
2
我不希望它一直在底部可见,我想要它粘附在页面的末尾,但是如果页面“变长”,你需要向下滚动,然后才能看到页脚。 - mheonyae
4个回答

69

你可以尝试使用position: fixed来实现这个效果。

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

你需要对页面底部进行偏移,因此建议在 .main 中添加一个与页脚高度相等的 padding-bottom

.main {
  padding-bottom: 30px /*whatever the height of your footer is*/
}

3
你可以使用 display: flex 轻松实现此操作。 您不需要关心 bodywrapper 标签的高度。 示例: 如果您想要更改 main 标签 的高度,请将其更改为任何值,footer 将始终保持在底部(不是 position: fixed)。

https://codepen.io/tronghiep92/pen/dzwRrO

HTML标记
<div id="wrapper">
   <header>my header</header>
   <main>main content, please change height</main>
  <footer>
    my footer
  </footer>
</div>

CSS解决方案
#wrapper {
  display: flex;
  flex-direction: column;
  min-height: 100vh;
}

header {
  height: 100px;
  background: yellow;
}

footer {
  height: 50px;
  background: red;
  margin-top: auto; /* this is the solution */
}

main {
  height: 100px
}

或者你可以:

#wrapper {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  min-height: 100vh;
}

header {
  height: 100px;
  background: yellow;
}

footer {
  height: 50px;
  background: red;
}

main {
  flex: 1;
  height: 100px;
}

3

Pritesh Gupta的解决方案对我非常有效:

如果他们的网站关闭,我会复制并粘贴代码:

以下是HTML代码:

<!DOCTYPE html>
<html>
  <head>
    <title>Sticky Footer</title>
  </head>

  <body>
    <main>stuff</main>
    <footer>&copy; 2016</footer>
  </body>
</html>

这是 CSS:

body {
  margin: 0;
}

main {
  min-height: calc(100vh - 4rem);
}

footer {
  height: 4rem;
}

我不知道它是否适用于旧版浏览器,但我个人并不太担心这个问题。

它还取决于您知道页脚的高度,尽管值得指出的是,您不一定必须像上面的代码中手动设置高度,因为如果您知道内容具有多少垂直填充和行高,您可以随时计算出高度...

希望这可以帮助您,我在找到这种技术之前花了大部分时间尝试网络上的每个固定页脚教程,虽然其他技术确实有效,但这种方法需要最少的努力。


2
如果你需要粘性页脚,可以使用以下两种解决方案。
解决方案1:
HTML:
<div class="wrap">
    Content
</div>
<div class="footer">
    Sticky Footer
</div>

CSS:

body, html, .wrap{
  height:100%;
}

body > .wrap{
  height:auto;
  min-height:100%;
}

.wrap:after {
  content: "";
  display: block;
  height: 100px; 
}

.footer{
  background:#662e8c;
  margin-top:-100px;
  height:100px;
  color:#fff;
  position:relative;
  line-height:180%;
  padding:0 10px;
}

示例: https://jsfiddle.net/ta1amejn/


解决方案2(使用表格属性):

HTML: 内容 底部

CSS:

body{
    display:table;
    width: 100%;
}

html, body{
    height:100%;
}

.main{
    height:100%;
    width:100%;
    padding-bottom:20px;
    background:#eee;
    display:table-row;
}

.footer{
    /*height:30px;*/
    line-height:30px;
    width:100%;
    background:#00f0ad;
    display:table-row;
}

示例:https://jsfiddle.net/zbtaoq1b/


如果您想要一个固定的页脚,请使用以下解决方案:

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

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