通过css使用background-color为背景图添加遮罩效果的两种方法

一个div同时设置background-color和background-image的话,color是处于img层下方的,无法实现遮罩效果,所以需要再创建一个div作为其子div,然后设置子div的背景颜色,介绍两种方法:

第一种,代码如下:

css:
 

.wrap{
    position: relative;
    background: url(i/pic4.jpg) no-repeat;
    -webkit-background-size: 100%;
    background-size: 100%;
}
.warp-mask{
    height:100%;
    width:100%;
    background: rgba(0,0,0,.4);
}

html:
 

<div class="wrap">
    <div class="wrap-mask"></div>
</div>

第二种,通过after伪元素设置,代码如下:

css:
 

.wrap{
    position: relative;
    background: url(i/pic4.jpg) no-repeat;
    -webkit-background-size: 100%;
    background-size: 100%;
}
.wrap-mask:after{
    position: absolute;
    top: 0;
    left: 0;
    content: "";
    background-color: yellow;
    opacity: 0.2;
    z-index: 1;
    width: 100%;
    height: 100%;
}

html:

<div class="wrap">
    <div class="wrap-mask"></div>
</div>

总结

以上所述是小编给大家介绍的通过css使用background-color为背景图添加遮罩效果,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对来客网网站的支持!