需求
一个div设置了background: url,现在需要使图片背景模糊,div内的文字清晰显示。
实现原理
背景图处于父级div,内容处于子级div,通过css设置背景给父级div的伪类元素before模糊度。其中父级元素为相对定位,父级伪类元素before为决定定位。
即可代码:
html结构
<div class="bg">
<div class="content">
文字内容
</div>
</div>
css样式
*{
margin: 0;
padding: 0;
}
.bg {
height:600px;
text-align: center;
line-height: 600px;
position: relative;
/*可以加上下面注释代码,可以让边缘不那么唐突*/
/* background: url('timg.jpg') no-repeat;
background-size:cover; */
/*也可以加入背景透明,使页面不那么唐突*/
background-color: rgba(0,0,0,.5);
}
.bg::before{
content:'';
background: url('timg.jpg') no-repeat;
background-size:cover;
filter: blur(5px);
position: absolute;
top:0;
bottom:0;
left:0;
right:0;
z-index: -1;
}
.content {
color: #ffffff;
font-size: 40px;
}