【问题标题】:Remove white space below footer [closed]删除页脚下方的空白 [关闭]
【发布时间】:2016-03-15 06:40:29
【问题描述】:

我的页脚下方总是有一个很大的空白区域。如何确保页面在页脚末尾结束?

【问题讨论】:

  • 显示html,然后有人可以帮助你
  • 请在您的问题中发布完整的代码示例。
  • 页眉和页脚之间的 div 增加,但更多我们需要代码
  • 好像你需要一个粘性页脚:css-tricks.com/snippets/css/sticky-footer

标签: html css footer removing-whitespace


【解决方案1】:

这个问题有三种解决方案

在以下所有示例中,我只是一个非常基本的 HTML 模板,只使用了三个 div:页眉、内容和页脚。所有选项都已缩小,但在更高级的网站上应该可以正常工作。

  1. 使用背景色

为正文和页脚设置相同的背景颜色。

body {
  margin: 0px;
  font-family: Arial;
  line-height: 20px;
  background-color: red;
}
#header {
  height: 20px;
  background: #222;
  color: white;
}
#content {
  background: gray;
  height: 200px;
}
#footer {
  height: 20px;
  background: red; /*Same as body, you could also use transparent */
  color: white;
}
<div id="header">
  Header
</div>
<div id="content">
  Content
</div>
<div id="footer">
  Footer
</div>
  1. 使用粘性页脚

使用固定在浏览器窗口底部的粘性页脚。 (我不推荐这个选项,因为很多用户不喜欢粘性页脚。但是你可以使用粘性页眉)

body {
  margin: 0px;
  font-family: Arial;
  line-height: 20px;
}
#header {
  height: 20px;
  background: #222;
  color: white;
}
#content {
  height: 2000px;
}
#footer {
  position: fixed;
  width: 100%;
  bottom: 0;
  left: 0;
  height: 20px;
  background: #222;
  color: white;
}
<div id="header">
  Header
</div>
<div id="content">
  Content
</div>
<div id="footer">
  Footer
</div>
  1. 对内容使用最小高度

为内容 div 设置一个最小高度,等于浏览器窗口高度减去页眉和页脚的高度。 (这是我个人最喜欢的,因为它可以跨浏览器工作并且在所有屏幕上都能响应)

body {
  margin: 0px;
  font-family: Arial;
  line-height: 20px;
}
#header {
  height: 20px;
  background: #222;
  color: white;
}
#content {
  min-height: calc(100vh - 40px);
}
#footer {
  height: 20px;
  background: #222;
  color: white;
}
<div id="header">
  Header
</div>
<div id="content">
  Content
</div>
<div id="footer">
  Footer
</div>

【讨论】:

  • 很棒的反应。第三种是我的首选方法,只要您只需要支持现代浏览器即可。 Modernizr 当然可以检查用户的浏览器是否支持 calc 和 vh。我认为这属于渐进增强的范畴,所以可能不需要某种 JS 回退。
【解决方案2】:

实现这一点的最简单方法是将 min-height 设置为页脚上方的内容,如下所示:

HTML:

<body>
    <section>
        This is content of the page
    </section>
    <footer>
        Text of footer
    </footer>
</body>

CSS:

section {
    min-height: 100vh; /* minus the height of the footer */
}

jsfiddle 链接:https://jsfiddle.net/x55xh3v7/


但更“优化”的解决方案是sticky footer techique,它可以防止页脚不必要地流出页面。

【讨论】:

    【解决方案3】:

    这样也可以

    #main{
      border:solid;
      height:100vh;
    }
    #footer{
      border:solid;
    }
    <div id="main">
    Everything here
    </div>
    <div id="footer">
    footer
    </div>

    【讨论】:

    • 在正文中添加 100vh 可以修复它!谢谢!
    【解决方案4】:

    我建议使用 javascript 来解决这个问题,如下所示:

    if($(window).height() > $("body").height()){
       $("footer").css("position", "fixed");
    } else {
       $("footer").css("position", "static");
    }
    

    【讨论】:

    • 只要可以用纯 css 解决,javascript 就是过大的杀伤力
    • 这可以用 CSS 完成,不需要使用 javascript,尤其是包括 JQuery-不必要的膨胀。