页面底部的正文背景和页脚

Body background and footer on bottom of page

我找不到这个问题的解决方案。我想要一个始终位于底部的页脚(不是 sticky/fixed),以及一个始终位于底部的背景(不是 sticky/fixed)。

为了更清楚我拍了一张图:https://i.imgur.com/qVLb1bl.png

<html>
 <div id="container">
  <div class="content">
   <h1>Content</h1>
  </div>
  <div class="footer">
   <h2>Footer</h2>
  </div>
 </div>
</html>

CSS:

html, body { height: 100%; }

body { display: flex; flex-direction: column; background: url('http://www.freetoursbyfoot.com/wp-content/uploads/2013/08/New-York-Skyline-Downdown-view.jpg') no-repeat bottom center; }

#container { display: flex; flex-direction: column; height: 100%; }

.content { max-width: 800px; width: 100%; height: 400px; margin: 0 auto; background: #eee; margin-top: 20px; text-align: center; padding-top: 30px; }

.footer { max-width: 800px; width: 100%; height: 100px; background: #000; margin: auto auto 0 auto; }

我也做了一个代码笔:https://codepen.io/nickm10/pen/XVJjGb

有人知道解决方案吗?

谢谢!

指定html页面的高度。否则页面足够高以适应您的所有元素; html, body { height: 1000px; }

对 html 和正文使用 min-height: 100%; 而不是 height: 100%;

更新的答案:

html 高度应设置为最小高度,以便在需要时可以增长。但是由于这个主体不知道父 (html) 元素的高度,所以我们不能再在那里使用基于 % 的最小高度。 谢天谢地,我们有视口单位。所以对于 body set min-height: 100vh; 这告诉 body 至少是视口高度的 100%。

html { min-height: 100%; }
body { min-height: 100vh; margin: 0; }

PS!您还需要使用此解决方案从 body 中删除边距。或者会有一个始终可见的滚动条。

因为您已经在使用 flexbox 布局。有一个叫做 flex-grow 的东西(flex-grow 属性 指定项目相对于同一容器内的其余灵活项目的增长量)。

只要给:

.content{
    -webkit-flex-grow: 1;    
    flex-grow: 1;
   /** remove height **/
}

并删除 .content 的高度。

将背景放在 body 伪元素中并在那里对齐。

body {
  ...
  position: relative;
  min-height: 100%;
  ...
}
body::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  top: 0;
  background: url("http://www.freetoursbyfoot.com/wp-content/uploads/2013/08/New-York-Skyline-Downdown-view.jpg")
    no-repeat bottom center;
  pointer-events: none;
  z-index: -1;
} 

这是一个代码笔:codepen.io/anon/pen/vpEgxo

希望这会有所帮助 ;)