background-clip的正確使用姿勢

  • 2019 年 12 月 10 日
  • 筆記

background-clip的正確使用姿勢

前幾天遇到一個問題:問如何通過背景色來顯示相反的文本顏色。 如果通過JS的話,可以灰常輕鬆的解決這個問題,但是純用CSS的話也不是不可能的。 這就需要用到今天的主角background-clip了。

background-clip是個啥

background-clip可以用來控制背景圖片/顏色的填充範圍。 我們知道,默認的background會填充盒模型的content+padding+border區域內。(可以將border顏色設為透明進行觀察)

現在,我們可以通過設置background-clip來控制背景填充的範圍。

background-clip的有效屬性值

border-box

設置填充範圍到border,這個也是默認的選項。 圖中的border應為淺灰色,因為後邊有藍色的背景色,所以導致border顏色變成了深藍色。

padding-box

設置填充範圍到padding,也就是說,border將不會有background的填充。

content-box

僅填充content區域。。

text

最後一個屬性值,目前webkit上還沒有標準版的實現,只能通過-webkit-background-clip來使用。 想要看到效果,我們需要將字體顏色設為透明 or 半透明。 效果如下:

來一個四種效果的對比圖:

截圖來自MDN

回到之前的問題

最開始我們說過的那個問題,如何根據背景色來顯示反色文本。 實現方式如下:

  1. background-color: inherit來繼承父元素的屬性值。
  2. background-clip: text來確保背景色只會填充到文字區域
  3. color: transparent來將文本顏色設為透明
  4. 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: ;  }