给背景img一个不透明度

时间:2015-11-24 09:23:38

标签: html css background-image opacity

我正在尝试为我的整页背景图像添加不透明度,但是当我添加不透明度代码时,我的整个html得到的不透明度为0.4会占用图像。

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

Source

我试图像这样添加不透明度:

html { 
  background: url(../img/bg2.jpg) no-repeat center center fixed; 
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
  opacity: 0.4;
}

但正如我所说,我的整个html变为0.4

我尝试在background: url(../img/bg2.jpg) no-repeat center center fixed 0.4;之后添加0.4但是我的图像只是空白了。

如何仅将0.4添加到我的背景图像?

3 个答案:

答案 0 :(得分:1)

尝试使用::after伪类:

html::after {
  content: "";
  background: url(../img/bg2.jpg) no-repeat center center fixed; 
 -webkit-background-size: cover;
 -moz-background-size: cover;
 -o-background-size: cover;
  background-size: cover;
  opacity: 0.4;  
  position: absolute; 
  top: 0; 
  left: 0; 
  right: 0; 
  bottom: 0;
  z-index: -1;
}

答案 1 :(得分:0)

同时为opacity设置body,然后重试:

body {
   opacity : 1;
}

答案 2 :(得分:0)

在这些情况下,我在body标签上使用:after psuedo元素,以及一些绝对定位和不透明度属性:https://jsfiddle.net/kc0sf39r/

<强> HTML:

<body>
  content
</body>

<强> CSS:

body {
    background: url("http://digital-photography-school.com/wp-content/uploads/flickr/205125227_3f160763a0_o.jpg") no-repeat;
    width: 100%;
    height: 100vh;
    position: relative;
}
body:before {
    position: absolute;
    top: -99px;
    bottom: -99px;
    left: -99px;
    right: -99px;
    background-color: red;
    content: " ";
    opacity: 0.5;

}