【问题标题】:How to keep <footer> always at the bottom of page,( not screen) in html5如何在 html5 中保持 <footer> 始终位于页面底部(不是屏幕)
【发布时间】:2016-03-08 06:37:39
【问题描述】:

我知道这可能是一个老问题,但是我尝试了很多方法,如果内容很轻,例如 2 行,页脚会出现并留下很多空间。这是我的代码:

<html>
 <head></head>
<body>
  <div class='navbar'></div>
  <div class='maincontent'> main content</div>
  <footer class='footer-box'>
    footer content
  </footer>
</body>
</html>

我尝试将位置设置为相对或绝对,但它们都不适合我,我需要始终将页脚定位在页面底部,无论 maincontent 的内容如何。任何想法?非常感谢!

【问题讨论】:

  • 你自相矛盾。如果只有一点内容,那么 页面的底部,但您似乎希望页脚位于屏幕底部。无论如何,我有 99% 的把握这是多次受骗(请参阅右侧的相关链接)。
  • sticky footer question的可能重复

标签: html css


【解决方案1】:

据我所知,您希望页脚位于视口底部,除非主要内容大到足以到达它,在这种情况下,您希望页脚位于页面底部。

在我看来,这是最好/最干净的方法:

请注意,这不是 JavaScript 解决方案,我已经添加了 JS,因此您可以看到不断增长的 .maincontent 块的效果。运行下面的代码 sn -p 看看我的意思。

function addContent() {

  $('.maincontent').append('<p>more content</p>');

}
html {
  height: 100%;
}
body {
  position: relative;
  margin: 0;
  min-height: 100%;
}
.maincontent {
  padding-bottom: 1em;
  /* or the footer height */
}
.footer-box {
  position: absolute;
  bottom: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<html>

<head></head>

<body>
  <div class='navbar'>
    <button onclick="javascript:addContent()">add content</button>
  </div>
  <div class='maincontent'>main content</div>
  <footer class='footer-box'>
    footer content
  </footer>
</body>

</html>

【讨论】:

    【解决方案2】:

    看来您正在使用引导程序,所以这对您有用

     <div class="navbar navbar-default navbar-fixed-bottom">
        </div>
    

    【讨论】:

    • 你怎么知道 OP 正在使用bootstrap
    • 除非涉及引导程序,否则很少使用导航栏
    【解决方案3】:

    即使问题得到了解答,我也想提出一个使用 flexbox 的解决方案。

    html {
      height: 100%;
    }
    
    body {
      min-height: 100%;
      display: -webkit-box;
      display: -webkit-flex;
      display: -ms-flexbox;
      display: flex;
      -webkit-box-orient: vertical;
      -webkit-box-direction: normal;
      -webkit-flex-direction: column;
      -ms-flex-direction: column;
      flex-direction: column;
    }
    
    main {
      -webkit-box-flex: 1;
      -webkit-flex: 1 0 auto;
      -ms-flex: 1 0 auto;
      flex: 1 0 auto;
      background: blue;
    }
    
    footer{
      height: 70px;
      background: yellow;
    }
    <main>
      Main content
    </main>
    
    <footer>
      Footer
    </footer>

    【讨论】:

      【解决方案4】:

      将 css 属性添加到页脚元素:

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

      直播DEMO

      【讨论】:

      • 我不明白我的回答是否反对......我给出的解决方案是有效且正确的...... !!!
      【解决方案5】:

      试试这个:

      footer.footer-box {
          position: fixed;
          left: 0;
          bottom: 0;
          width: 100%;
      }
      

      【讨论】:

      • 为什么会得到 -1 ?这正是“我需要始终将页脚放置在页面底部,无论 maincontent 的内容。”问题的答案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-11
      • 2011-11-24
      • 1970-01-01
      • 1970-01-01
      • 2014-07-05
      • 2014-06-17
      • 2012-01-26
      相关资源
      最近更新 更多