background-clip
设置元素的背景(背景图片或背景颜色)是否延伸至
border-box
下,padding-box
下, 或者content-box
下
clip
本身就有修剪
的意思~
语法
- 如果元素没有
background-image
或background-color
, 那么这个属性只有在边框有透明部分或者部分透明区域(比如border-style
为dashed
)才能看到效果, 否则边框将会覆盖background-clip
产生的样式. 关键词属性
border-box
:默认值
. 背景延申至border
的外沿, 但是在z
方向上仍在border
下层.padding-box
: 背景延申至padding
的外沿, 不会绘制在边框下面.content-box
: 背景被裁剪至content
内容区text
: 背景被裁减成文字的形状
- 看一段示例
-
<div class="box box9">你好<br>世界9</div> <div class="box box10">你好<br>世界10</div> <div class="box box11">你好<br>世界11</div> <div class="box box12">你好<br>世界12</div>
-
.box { width: 200px; height: 200px; background-image: url(../../float/fish.png); /* background-repeat: no-repeat; */ border: 15px dashed salmon; padding: 1rem; font-size: 2em; text-align: center; color: #fff; } .box9 { -webkit-background-clip: border-box; background-clip: border-box; } .box10 { -webkit-background-clip: padding-box; background-clip: padding-box; border-color: aquamarine; } .box11 { -webkit-background-clip: content-box; background-clip: content-box; border-color: skyblue; } .box12 { -webkit-background-clip: text; background-clip: text; color: transparent; font-size: 3em; font-weight: bold; }
-
这四个背景的
background-clip
分别为content-box
,padding-box
,content-box
和text
, 可以看到图片的默认根据background-position: left top;
展示的, 只不过clip(被裁掉)
了不同的区域. -
📕注意点
1️⃣
, 如果想要background-clip: text
生效, 注意将color
属性设置为transparent
或者带有alpha
通道的颜色, 不然纯黑的文字颜色就挡死背景了😅 -
📕注意点
2️⃣
: 当background-clip
值为border-box
时, 注意background-repeat
不能是no-repeat
, 参考下面的对比- 左边的是
repeat
, 右边的是no-repeat
. 来解释一下为什么no-repeat
会这样展示? - 根据
background-position
的默认值left top
和background-origin
的默认值padding-box
, 就自然左上角和padding
的边界对齐
- 左边的是
-
- 在移动端
iOS 14
版本才部分支持background-clip
属性, 所以要加上-webkit-background-clip
私有属性.
应用
- 苹果官网由很多这样的例子, 来看最新发布的 iPad Air 5 的产品介绍页
-
<div class="air5"> Light. Bright.<br> Full of might. </div>
-
.air5 { width: 300px; height: 100px; font-size: 2rem; font-weight: bold; color: transparent; padding: 10px; -webkit-background-clip: text; background-clip: text; background-image: linear-gradient(90deg, #dc79ff, #256bfa); }
注
- 图片来自 unsplash, 仅作个人学习使用, 感谢