实现背景图片透明而内容不透明有很多种方法,但是我最常用的是用before伪元素。
大家肯定都知道透明是使用opacity,但opacity会让背景及其子元素的所有内容都透明,比如:
<style>
* {
margin: 0;
padding: 0;
}
.box1 {
width: 500px;
height: 340px;
position: absolute;
top: 50%;
left: 50%;
margin-left: -250px;
margin-top: -170px;
opacity: 0.5;
background-image: url("./StudyCode/HTML5+CSS3/图片/哈利波特7.png");
}
.box2{
width: 200px;
height: 150px;
font-size: 40px;
font-weight: 500;
position: absolute;
top: 50%;
left: 50%;
margin-left: -100px;
margin-top: -75px;
text-align: center;
line-height: 150px;
letter-spacing: 10px;
}
</style>
</head>
<body>
<div class="box1">
<div class="box2">哈利波特</div>
</div>
</body>
</html>
得到的结果如下:可以看见其中的字体也被透明了
在上面的css中加上如下代码即可解决:记得把上面的.box1的最后两行代码删掉,不然会覆盖before的内容。
.box1::before{
width: 500px;
height: 340px;
content: "";
/* 一定要加定位,这样z-index才起作用 */
position: absolute;
top: 50%;
left: 50%;
margin-left: -250px;
margin-top: -170px;
z-index: -1;
opacity: 0.5;
background-image: url("./StudyCode/HTML5+CSS3/图片/哈利波特7.png");
}
得到结果: