background-size:封面不包括整个可滚动页面

时间:2018-02-20 18:07:51

标签: css css3 background-image background-size

我正在尝试将图像作为背景。背景图像应覆盖整个可滚动页面(宽度+高度)。并且背景图像不应该被修复,它也应该滚动。

以下是示例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>

由于

1 个答案:

答案 0 :(得分:1)

删除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>

相关问题