背景不透明度,而不会破坏div的内容

时间:2018-07-12 17:59:10

标签: html css background-image frontend

我的意思是我有<section>标签和background-image: url(...),我想知道如何更改背景的不透明度,但不更改子标签的不透明度。

这是我的代码:

section {
    	background-size: cover;
    	margin: 0px;
          	background: red;
    	padding: 10px 10px 10px 10px;
    	background-repeat: no-repeat;
    		background-position: center;
    }
    #study {
    	background-image: url(2.jpg);
    }
    h1,h2 {
font-weight: 1000;
font-size: 60px;
text-align:center;
color: black;
letter-spacing: 5px;
z-index: 500;
user-select:none;
}
#study:hover {
opacity: 0.8
}
        <section id=study>
        <h2>Text</h2>
<h2>But text gets lighter too!</h2>
</section>

1 个答案:

答案 0 :(得分:1)

使用伪元素:

http://jsfiddle.net/2dauqf9o/6/

section {
  position: relative;
  text-align: center;
  padding: 120px 0;

  &:after {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: red;
    content: '';
    transition: all .15s ease-in-out;
  }
}

h2 {
  position: relative;
  z-index: 1;
}


// Hover
section:hover {

  &:after {
    opacity: .6;
  }
}
相关问题