没有位置的叠加效果:固定;

时间:2016-12-08 14:19:31

标签: html css css3 css-position

我想要一个带有叠加效果的背景图片。

请参阅:https://jsbin.com/giqagidufe/edit?html,css,output

叠加效果应始终为全屏尺寸 - 同样在调整大小时。我第一次使用:

html, body { min-height: 100%; }

// Background Image
body {
    position: relative;
    background-image: url("/_Resources/Static/Packages/VMP.Website/Images/Header/header_full.jpg");
    background-position: top center;
    background-repeat: no-repeat;
    margin: 0px;
    background-color: black !important;
}

// Colored overlay of Background Image
body::before {
    position:absolute;
    content: '';
    background-color: rgba(44, 62, 80, 0.7);
    min-width: 100%;
    height: 100%;
    z-index: -10; 
}

所以我使用了position:absolute;但是这个问题没有完全覆盖整个屏幕。我用position:fixed;解决了这个问题。

但这迫使浏览器在每个滚动条上重新渲染整个内容,因此它不是最佳选择。

我还能做其他选择吗?一个性能更高的人?

3 个答案:

答案 0 :(得分:2)

如果我们在同一页面上,这就是你要找的东西。 如果这可以解决您的问题,请告诉我。

您应该将两个元素(图像和叠加层)放在绝对位置。 您可以使用类叠加的RGBA属性的最后一个参数来设置不透明度。

它完全响应,坚持你的问题。 这是一个fiddle

<强> HTML         

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="script.js"></script>
  </head>

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

</html>

<强> CSS

html, body { min-height: 100%; }
body {
    padding: 0;
    border: 0;
    width:100%; 
    height:100%; 
    margin: auto;
    position: absolute;
    top: 0; left: 0; bottom: 0; right: 0;
    background-image: url("http://wallpapercave.com/wp/8fWGVfB.jpg");
    background-position: top center;
    background-repeat: no-repeat;
}
.overlay{
    width:100%; 
    min-height:100%; 
    background-color: rgba(0,0,0,0.4);
    position: absolute;
}

答案 1 :(得分:0)

您可以做的是将background-attachment: fixed添加到body标记中。无论body的高度如何,这都会保持背景固定。

html,
body {
  height: 100%;
}
body {
  height: 1000px;
  margin: 0;
  background-image: url(http://hdwallpaper20.com/wp-content/uploads/2016/04/4k-wallpaper-15-ULTRA-HD-Collections-Yosemite-Valley-Snow-Sunset-4K-Ultra-HD-Desktop-Wallpaper-1024x576.jpg);
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  background-attachment: fixed;
}
body:after {
  content: '';
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.3);
}
<body>
  <div>Can be a div with some content</div>
</body>

答案 2 :(得分:0)

尝试将此代码添加到您的身体:

  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;