将alpha / opacity应用于背景图像

时间:2015-11-26 16:04:19

标签: html css css3

如何在不影响文字颜色的情况下使背景图像变暗?

http://jsfiddle.net/tx58qf3m/



div {
    display:block;
    background:url('http://placehold.it/500x500') 0 0 no-repeat;
    background-color:rgba(0, 0, 0, 1);
    background-size:cover;
    height:500px;
    width:500px
}
    
    

<div>
    
    <h1>Hello, it's me!</h1>
    
</div>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:1)

使用:before

div {
    display:block;
    background:url('http://placehold.it/500x500') 0 0 no-repeat;
    background-color:rgba(0, 0, 0, 1);
    background-size:cover;
    height:500px;
    width:500px
}
  div:before {
  content: "";
  position: absolute;
  width: 100%; 
  height: 100%;  
  opacity: .4; 
  z-index: 1;
  background-color:black
}  

http://jsfiddle.net/tx58qf3m/14/

答案 1 :(得分:1)

如您所见,更改父元素will affect the child elementopacity,即示例中的h1

您可以使用一些不同的选项来完成此操作,而不会影响子元素。

1)在图像编辑器中编辑opacity(显而易见并占用最少的代码)

2)使用伪元素来包含背景图片并在那里进行opacity更改 - DEMO

3)不要将background-image应用于div,而是制作另一个子元素以包含图片 - DEMO

请勿忘记调整z-index值。

答案 2 :(得分:0)

喜欢这个

 <style>

 Div {
  Position:relative;
}

 Div:before {
  Content:'';
  Position:absolute;
  Top:0;
  Left:0;
  Background-color:rgba (0,0,0,.5);
  Width:100%;
  Height:100%;
  Z-index:2;
  }

 Div H2 {
 Position:relative;
 Z-index:3;
 }
  </style>