前几天遇到一个问题:问如何通过背景色来显示相反的文本颜色。 如果通过JS的话,可以灰常轻松的解决这个问题,但是纯用
CSS的话也不是不可能的。 这就需要用到今天的主角background-clip了。
background-clip可以用来控制背景图片/颜色的填充范围。
我们知道,默认的background会填充盒模型的content+padding+border区域内。(可以将border颜色设为透明进行观察)


现在,我们可以通过设置background-clip来控制背景填充的范围。
设置填充范围到border,这个也是默认的选项。
图中的border应为浅灰色,因为后边有蓝色的背景色,所以导致border颜色变成了深蓝色。

设置填充范围到padding,也就是说,border将不会有background的填充。

仅填充content区域。。

最后一个属性值,目前webkit上还没有标准版的实现,只能通过-webkit-background-clip来使用。
想要看到效果,我们需要将字体颜色设为透明 or 半透明。
效果如下:

来一个四种效果的对比图:

最开始我们说过的那个问题,如何根据背景色来显示反色文本。 实现方式如下:
background-color: inherit来继承父元素的属性值。background-clip: text来确保背景色只会填充到文字区域color: transparent来将文本颜色设为透明filter: invert(100%)来实现反色滤镜.back {
background: blue;
width: 100px;
height: 100px;
display: inline-block;
}
.back:nth-of-type() {
background: red;
}
.back:nth-of-type() {
background: green;
}
.back:nth-of-type() {
background: yellow;
}
.back:nth-of-type() {
background: pink;
}
.back:nth-of-type() {
background: black;
}
.back:nth-of-type() {
background: white;
}
.text {
background: inherit;
-webkit-background-clip: text;
color: transparent;
filter: invert(100%);
}
通过background-clip: text可以做很多有意思的事儿,比如说渐变色的文字。
结合着animation甚至可以实现动态的渐变色字体。
P.S. Animate.css首页的标题效果就是通过这个方式来实现的。
* {
margin: ;
padding: ;
}
body {
position: relative;
width: 100vw;
height: 100vh;
background-color: #9E9E9E;
}
.box1 {
position: absolute;
width: 50%;
padding-top: 25%;
background-color: #3F51B5;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
z-index: ;
}