DigitalOcean 为您的旅程的每个阶段提供云产品。从 免费赠送的 200 美元信用额度开始!
background-clip
允许您控制背景图像或颜色在元素的填充或内容之外延伸的程度。
.frame {
background-clip: padding-box;
}
值
border-box
是默认值。这允许背景延伸到元素边框的外边缘。padding-box
在元素填充的外边缘裁剪背景,不允许其延伸到边框中。content-box
在内容框的边缘裁剪背景。inherit
将父级的background-clip
设置应用于所选元素。
演示
background-clip
最好在实际操作中解释,因此我们创建了两个演示来展示其工作原理。
在第一个演示中,每个 div 都有一个段落。该段落是 div 的内容。每个 div 都有一个黄色背景和一个 5 像素的半透明浅蓝色边框。
默认情况下,或者设置了 background-clip: border-box
,黄色背景会一直延伸到边框的外边缘。请注意,由于下面的黄色背景,边框看起来像是绿色的。
当 background-clip
更改为 padding-box
时,背景颜色会在元素的填充结束处停止。请注意,边框是蓝色的,因为背景不允许渗透到边框中。
使用 background-clip: content-box
,背景颜色只应用于 div 的内容,在本例中是单个段落元素。div 的填充和边框没有背景颜色。但是,有一个值得一提的小细节:颜色确实延伸到了内容的边距中。查看使用 content-box
的第一个和第二个示例之间的区别。
在第一个 content-box
示例中,浏览器默认边距应用于段落,背景在边距之后裁剪。在第二个示例中,边距在 CSS 中设置为 0,背景在文本边缘裁剪。
下一个交互式演示展示了使用背景图像的 background-clip
。此演示中的内容是一个较小的空 div。
此演示除了 background-clip
之外,还应用了 background-size: cover
和 background-repeat: no-repeat
来控制背景图像,否则背景图像会重复直到裁剪。
文本
有一个供应商前缀版本可以用于将背景裁剪到文本。为了查看该版本的工作原理,文本也需要是透明的。幸运的是,还有一个供应商前缀文本颜色属性可以有效地覆盖 color
,使其可以安全地使用,因为它可以有回退
.background-clip-text {
/* if we can clip, do it */
-webkit-text-fill-color: transparent;
-webkit-background-clip: text;
/* what will show through the text
~ or ~
what will be the background of that element */
background: whatever;
/* fallback text color
~ or ~
the actual color of text, so it better work on the background */
color: red;
}
Firefox、Chrome 和 Safari 支持此功能。
浏览器支持
IE | Edge | Firefox | Chrome | Safari | Opera |
---|---|---|---|---|---|
9+ | 12+ | 22+ | 21+ | 5.1+ | 15+ |
iOS Safari | Android Chrome | Android Firefox | Android 浏览器 | Opera Mobile |
---|---|---|---|---|
全部 | 全部 | 全部 | 3+ | 62+ |
更多信息
相关属性
背景
.element { background: url(texture.svg) top center / 200px 200px no-repeat fixed #f8a100; }
背景附件
.hero { background-attachment: fixed; }
背景混合模式
.element { background-blend-mode: screen; }
背景裁剪
.element { background-clip: padding-box; }
背景颜色
element{ background-color: #ff7a18; }
背景图片
.element { background: url(texture.svg); }
背景原点
.element { background-origin: border-box; }
背景位置
.element { background-position: 100px 5px; }
背景重复
.element { background-repeat: repeat-x; }
背景尺寸
.element { background-size: 300px 100px; }
“text” 已被添加为允许值。
没错!这是一个很棒的功能,Chris 可以更新这篇文章。