使用
background-blend-mode
来实现简单的着色效果。
你可以使用
background-blend-mode
CSS 属性:
.box {
width: 300px;
height: 300px;
background-size: cover;
background-image: url('https://picsum.photos/300');
}
.background-tint {
background-color: rgba(200,100,0,.5);
background-blend-mode: multiply;
}
<div class="box background-tint"></div>
将其放置在具有背景图像的任何元素上,您就可以开始使用了。
该属性在现代浏览器中得到很好的支持,但不包括IE 11。对于不支持的浏览器,您可以使用
polyfill。
工作演示
其他选项
使用filter
进行复杂的着色
您可以使用filter
CSS属性:
.box {
width: 300px; height: 300px;
background-size: cover;
background-image: url('https://picsum.photos/300');
}
.background-tint {
filter: sepia(100%) saturate(200%) brightness(70%) hue-rotate(330deg);
}
<div class="box background-tint"></div>
将其放置在具有背景图像的任何元素上,然后您就可以开始使用了。
为了改变颜色,请改变
hue-rotate
的值。
该属性在现代浏览器中得到很好的支持,但不包括IE 11。
工作演示
使用平面线性渐变和多重背景叠加
.background-tint {
background-image:
linear-gradient( rgba(0,0,0,.5), rgba(0,0,0,.5) ),
url('http://placehold.it/420')
}
我认为这是最常用的技术,但它的缺点是硬编码,也就是说你不能只是拿一个类,贴在一个元素上并进行着色。
你可以将其转化为一个较少或者Sass的mixin,类似于:
less
.background-tint(@tint-color, @image-url) {
background-image:
linear-gradient( @tint-color, @tint-color ),
url( @image-url )
}
sass
@mixin background-tint($tint_color, $image_url) {
background-image:
linear-gradient( $tint_color, $tint_color ),
url( $image_url )
}
工作演示
使用透明背景
这种方法的优点是适用于大多数浏览器,并且只需将其添加到任何元素的一个漂亮的类中。
缺点是,如果该元素内还有其他内容,则必须将其包装在一个带有某种定位的 div 中,最好使用 position: relative
。
示例:
.box {
width: 300px; height: 300px;
background-size: cover;
background-image: url('https://picsum.photos/300');
color: #facebc;
}
.background-tint { position: relative; }
.background-tint::after {
content: "";
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
width: 100%;
height: 100%;
background-color: rgba(100,0,0,.5);
margin: auto;
}
.u-relative { position: relative; z-index: 1; }
<div class="box background-tint">
<div class="u-relative">300 x 300</div>
</div>
工作演示
div
内字体颜色的方法。 - pjammercolor
参数的颜色。 - hitautodestructfilter
属性,应该可以仅涵盖非透明区域。缺点是很难选择色调的颜色。 - hitautodestruct