背景图像与不透明度和封面整个屏幕

时间:2016-01-17 23:58:55

标签: html css css3 background-image

一直在玩CSS,出于某种原因,我无法让图像覆盖整个屏幕。我设法蘸了opacity,但图像不会覆盖屏幕。

<div class="backgroundImage">
    <img src="Image/BackgroundImage.jpg">
</div>
.backgroundImage{
    opacity: 0.4;
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

但是,如果我使用下面的代码,我可以覆盖整个屏幕,但opacity赢了。因此,由于某种原因,它不适用于div。

html { 
    background: url(images/bg.jpg) no-repeat center center fixed; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

3 个答案:

答案 0 :(得分:3)

您可以组合多个背景图像并将它们叠加在一起。但是没有办法控制它们的不透明度。

    .backgroundImage {
    background-image: url('http://www.css3.info/wp-content/themes/new_css3/img/sheep.png'), url('http://lorempixel.com/300/400');
    background-position: center bottom, left top;
    -webkit-background-size: 80px 60px, cover;
    -moz-background-size: 80px 60px, cover;
    -o-background-size: 80px 60px, cover;
    background-size: 80px 60px, cover;
    background-repeat: repeat-x, no-repeat;
    width: 100%;
    height: 100vh;
}

在您的情况下,img标记未关闭。它看起来应该是<img src="Image.jpg">

此外,您无法使用img background-size:width:来指定height:的尺寸。

答案 1 :(得分:2)

您可以使用:before:after的CSS伪元素,并为其设置背景图像+ opacity。您可以将所有内容设置为height:100%,也可以直接在div上使用height:100vh,以使其覆盖整个视口高度。

<强> Jsfiddle Example

&#13;
&#13;
body {
  margin: 0;
}
.container {
  position: relative;
  height: 100vh;
}
.container:before {
  background: url("https://unsplash.it/500") center / cover;
  content: '';
  position: absolute;
  left: 0; right: 0; top: 0; bottom: 0;
  z-index: -1;
  opacity: 0.5;
}
&#13;
<div class="container">Yes!</div>
&#13;
&#13;
&#13;

答案 2 :(得分:1)

以下是它的演示:https://jsfiddle.net/a1wvdpwc/17/ 我认为你想要的效果是什么?

只需给背景div的宽度和高度100%,并给它一个固定的位置。然后给它一个非常低的Z指数,使它保持在最后。然后,您还需要为图像提供100%的高度和宽度,以便填充视口。 (在演示中我使用了vh和vw;这意味着视口宽度和视口高度,以百分比表示。)

此外,演示版也在scss中,但唯一的区别是放在backgroundImage样式中的css Img使用了一个后代选择器,因此它定位所有作为div.backgroundImage下降的Img元素。我已经把这个编译后的CSS看起来像这个答案。

也很抱歉没有缩进。我在手机上输入了它。我会在几个小时内用更整洁的版本更新它。

html是:

<div class="backgroundImage">
      <img src="http://lorempixel.com/image_output/city-q-c-640-480-6.jpg" />
</div>
<div class="content">
    Content here
</div>

css是:

.backgroundImage {
    Position:fixed;
    Top: 0;
    Bottom: 0;
    Width: 100vh;
    Height: 100vh;
    Opacity: 0.25;
    Z-index: -5000;
}

.backgroundImage img {
    width:100vw;
    height: 100vh;
}
.content {
    padding: 30px;
}

此外,我忘了添加(据我所知)这种方法对于语义来说不太好,但如果你使用它就不会太糟糕。

相关问题