【问题标题】:background-size: cover does not cover the whole scrollable pagebackground-size: 封面不覆盖整个可滚动页面
【发布时间】:2018-02-20 18:07:50
【问题描述】:

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

这里是示例 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 sn-p 时,蓝色背景颜色根本不可见 - 它应该被背景图像覆盖。

有没有办法实现它?

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>

谢谢

【问题讨论】:

  • 为什么要对:after伪标签这样做。为什么不只是 body 标签
  • 我让它像那样工作。你想让我发帖作为答案吗
  • 蓝色 在 jsfiddle 中根本不可见...
  • @GerardoBLANCO 因为我用它做了一些过滤 - 例如模糊。但这与问题无关,因此我没有包含该信息。

标签: css background-image background-size


【解决方案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;
}
&lt;div class="content"&gt;&lt;/div&gt;

【讨论】:

  • 正如我一开始所说,我希望背景图像“不固定”,它应该在滚动时移动。可以以某种方式完成吗?
  • 就是这样!几乎。有没有机会让它与伪标签一起工作?由于额外的过滤(模糊等)
  • @TomC。是的,确定:) 正在更新
  • @TomC。看看
猜你喜欢
  • 1970-01-01
  • 2019-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-01
  • 2012-08-20
  • 1970-01-01
  • 2020-04-17
相关资源
最近更新 更多