天天看點

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

來激活。

繼續閱讀