天天看点

CSS-背景裁剪 | background-clip

background-clip

  设置元素的背景(背景图片或颜色)是否延伸到边框下面。

/* Keyword values */
background-clip: border-box;
background-clip: padding-box;
background-clip: content-box;
background-clip: text;

/* Global values */
background-clip: inherit;
background-clip: initial;
background-clip: unset;      

如果没有设置背景颜色或图片,那么这个属性只有在边框(border)设置为透明或半透明时才能看到视觉效果(查看 

border-style

border-image

),不然的话,这个属性造成的样式变化会被边框覆盖住。

初始值 border-box
适用元素 all elements. It also applies to ::first-letter and ::first-line.
是否是继承属性 no
适用媒体 visual
计算值 as specified
Animation type discrete
正规顺序 the unique non-ambiguous order defined by the formal grammar

语法

border-box

——背景延伸到边框外沿(但是在边框之下)。

padding-box

边框下面没有背景,即背景延伸到内边距外沿。

content-box

——背景裁剪到内容区 (

content-box) 

外沿。

text

背景被裁剪为文字的前景色。

正式语法

<box>#where 
<box> = border-box | padding-box | content-box      

示例

HTML

<p class="border-box">The background extends behind the border.</p>
<p class="padding-box">The background extends to the inside edge of the border.</p>
<p class="content-box">The background extends only to the edge of the content box.</p>
<p class="text">The background is clipped to the foreground text.</p>      

CSS

p {
  border: .8em darkviolet;
  border-style: dotted double;
  margin: 1em 0;
  padding: 1.4em;
  background: linear-gradient(60deg, red, yellow, red, yellow, red);
  font: 900 1.3em sans-serif;
  text-decoration: underline;
}

.border-box { background-clip: border-box; }
.padding-box { background-clip: padding-box; }
.content-box { background-clip: content-box; }

.text {
  background-clip: text;
  color: rgba(0,0,0,.2);
}      

结果

规范

Specification Status Comment
CSS Backgrounds and Borders Module Level 3The definition of 'background-clip' in that specification. Candidate Recommendation Initial definition.
CSS Backgrounds and Borders Module Level 4The definition of 'background-clip' in that specification. Editor's Draft Add text value.
纠错

浏览器兼容性

Feature Chrome Edge Firefox Internet Explorer Opera Safari
Basic Support 1.01 12 4.02 9.03 10.5 3.01
content-box 1.0 4.04 9.05 3.0
text (Yes) -webkit- 6 12 -webkit- 6 15 49.07 No
Android Chrome for Android Edge mobile Firefox for Android IE mobile Opera Android iOS Safari
4.1 (Yes) 14.0 7.1 12.1
?

1. Webkit的也支持此属性的前缀版本,在这种情况下,除了目前的关键字,作为替代的同义词有:

padding

border

,和

content

2. Gecko从版本1.1到版本1.9.2,对应于Firefox 1.0到3.6,支持一个不同的前缀语法:

-moz-background-clip: padding | border

3. 在IE 7和Internet Explorer的IE 8中,此属性总是表现得像

background-clip: padding

overflow

hidden

auto

,或

scroll

4. 仅支持属性的前缀版本; 根据

官方博客

,WebKit在裁剪中不包含文字装饰或阴影。

5. 在Firefox 48中,它不是默认激活的且对它的支持可以通过设置

layout.css.background-clip-text.enabled

true

来激活。

继续阅读