背景大小:封面没有覆盖整个可滚动页面

background-size: cover does not cover the whole scrollable page

我正在尝试将图像作为背景。背景图像应覆盖整个可滚动页面(宽度+高度)。而且背景图片不应该是固定的,应该是滚动的。

这里是例子html:

<html>
  <head></head>
  <body>
    <div class="content"></div>
  </body>
</html>

这是示例 css:

html, body
{
  height: 100% !important;
  overflow: auto !important;
}

body:before {
    content: "";
    position: fixed;
    display: block;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    z-index: -1;
    background-color: blue;
    background-repeat: no-repeat;
    background-position: center top;
    background-attachment: fixed;
    background-size: cover;
    background-image: url('https://static.pexels.com/photos/392018/pexels-photo-392018.jpeg');
}

.content {
    height: 1800px;
    width: 200px;
    background-color: white;
    margin: auto;
}

这里是JSFIDDLE

当您查看 JSFIDDLE 片段时,蓝色背景颜色根本不应该可见 - 它应该被背景图片覆盖。

有没有办法实现呢?

html,
body {
  height: 100% !important;
  overflow: auto !important;
}

body:before {
  content: "";
  position: fixed;
  display: block;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: -1;
  background-color: blue;
  background-repeat: no-repeat;
  background-position: center top;
  background-attachment: fixed;
  background-size: cover;
  background-image: url('https://static.pexels.com/photos/392018/pexels-photo-392018.jpeg');
}

.content {
  height: 1800px;
  width: 200px;
  background-color: white;
  margin: auto;
}
<html>

<head></head>

<body>
  <div class="content"></div>
</body>

</html>

谢谢

删除 height:100% 并改为 min-height。您还可以像这样简化代码:

body {
  min-height: 100%;
  background-color: blue;
  position:relative;
  margin:0;
}
body:before {
  content:"";
  position:absolute; 
  top:0;
  bottom:0;
  right:0;
  left:0;
  background-repeat: no-repeat;
  background-position: center top;
  background-size: cover;
  background-image: url('https://static.pexels.com/photos/392018/pexels-photo-392018.jpeg');
}

.content {
  height: 1800px;
  width: 200px;
  background-color: white;
  margin:auto;
  position:relative;
  z-index:1;
}
<div class="content"></div>