CSS set background transparency effect
There are two ways to set the background transparency effect:
- Use the opacity property to define the transparency, the range 0-1, 0 means completely transparent, 1 means opacity, advantage: can be used on the background image and background color. Disadvantages: The setting div and its sub-elements will be displayed transparently.
<div class="div1">
<p>透明度测试</p>
</div>
.div1{
display: inline-block;
margin: 10px;
width: 200px;
height: 200px;
color: #FFF;
background:url(img/middle-top-bg.png) no-repeat;
/* 填充整个容器 */
background-size: 100% 100%;
opacity: 0.3;
}
result:
- Use rgba(red, green, blue, alpha) to set the transparency, advantage: only the background color is transparent. Disadvantage: Cannot set background image.
<div class="div2">
<p>透明度测试</p>
</div>
.div2{
display: inline-block;
margin: 10px;
width: 200px;
height: 200px;
color: #FFF;
background-color: rgba(150,250,27,0.2);
}
result:
- If you want to use a background image and want to set the background transparent, but the content is not transparent, you can set a div as the background, and then make the div transparent. Advantages: It can be used on both the background picture and the background color. Disadvantages: It is troublesome to design multiple divs.
<div class="div3">
<div class="bg"></div>
<div class="container">
<p>透明度测试</p>
</div>
</div>
div3 {
display: inline-block;
margin: 10px;
width: 200px;
height: 200px;
color: #FFF;
}
.bg{
position: absolute;
background: url(img/middle-top-bg.png) no-repeat;
/* 填充整个容器 */
background-size: 100% 100%;
opacity: 0.3;
}
.container{
position: relative;
}
result: