移除页脚下方的空白

29

我的页脚下面总是有很大的空白区域。我该如何确保页面在页脚结束时结束?

示例


1
展示HTML代码,然后有人可以帮助你。 - Joel R Michaliszen
1
请在您的问题中发布完整的代码示例。 - j08691
增加页头和页脚之间的div,但是如果需要更多,我们需要代码。 - davbuc
2
似乎你需要一个固定页脚:https://css-tricks.com/snippets/css/sticky-footer/ - phynam
4个回答

41

这个问题有三种解决方案

在以下所有示例中,我仅使用了三个div:标题、内容和页脚来包含基本的HTML模板。所有选项都已被压缩,但在更高级的网站上也应该可以正常工作。

  1. 使用背景颜色

为body和footer设置相同的background-color。

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. 使用最小高度来控制内容

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

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>


3
非常棒的回复。只要您只需要支持现代浏览器,第三种方法就是我首选的方法。当然,Modernizr可以检查用户的浏览器是否支持calc和vh。我认为这应该属于渐进增强的范畴,因此可能不需要某种JS备用方案。 - Evan Donovan
非常好的答案。我选择了第三个选项。 - shamnad sherief

11
最简单的实现方法是将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/


更加“优化”的解决方案是粘性页脚技术,它可以防止页脚不必要地流出页面。


11

也可以像这样完成

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


2
将100vh添加到body中即可解决问题!谢谢! - Daksh M.

1

我建议使用JavaScript来解决这个问题,可以像这样:

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

只要可以用纯CSS解决,JavaScript就过于复杂了。 - markcheeky
这可以通过 CSS 完成,无需使用 JavaScript,特别是包括 JQuery - 不必要的庞杂。 - Oli C

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