设置背景半透明,文字不透明效果
一、常见的错误做法
最常见的做法就是:
1.设置元素的opacity,这种设置出来的效果就是内容与背景都是半透明的,严重影响视觉效果。
2.设置background-color:rgba(),这种方式只能设置背景颜色的透明度。
二、正确做法
有两种方法,原理相同:都是要增加一个新盒子,定位到它的上面去。
1.利用伪元素::before,我们通过给伪元素添加透明背景并且定位到元素中。
.demo {width: 300px;height: 300px;text-align: center;line-height: 50px;}.demo::before {content: '';/*放上自己喜欢的图片*/background: url(../img/cat.jpg) no-repeat;opacity: .3;background-size: cover;width: 300px;height: 300px;position: absolute;top: 0;left: 0;}
<div class="demo">背景图片透明,文字不透明</div>
2.增加一个盒子,我们通过给新盒子添加透明背景并且定位到元素中```css.main {position: relative;width: 300px;height: 300px;text-align: center;line-height: 300px;font-size: 20px;}.ax {position: absolute;top: 0;left: 0;width: 300px;height: 300px;background: url(../img/cat.jpg) no-repeat;opacity: .3;background-size: cover;}
<div class="main">背景图片透明,文字不透明<div class="ax"></div></div>