CSS 偽類函數(shù) :is() 和 :where()

在編寫 CSS 時(shí),有時(shí)可能會使用很長的選擇器列表來定位具有相同樣式規(guī)則的多個(gè)元素。例如,如果您想對標(biāo)題中的 <b> 標(biāo)簽進(jìn)行顏色調(diào)整,我們應(yīng)該都寫過這樣的代碼:

h1 > b, h2 > b, h3 > b, h4 > b, h5 > b, h6 > b {
  color: hotpink;
}

現(xiàn)在,我們可以使用 :is() 縮減代碼并提高其可讀性:

:is(h1,h2,h3,h4,h5,h6) > b {
  color: hotpink;
}

瀏覽器兼容性

:is() 由 :match() 改名而來,部分瀏覽器有其私有的 :any() 實(shí)現(xiàn) :is() 的部分功能,在使用 :is() 之前,我們應(yīng)該先了解其兼容性:


image.png

:is() 和 :where()

:is() 作為一個(gè)偽類函數(shù),其接收選擇器列表作為參數(shù),并選擇該列表中任意一個(gè)選擇器可以選擇的元素,:where() 偽類函數(shù)與其功能相同,僅僅選擇器權(quán)重不同,下面是幾個(gè)例子:

/* at the beginning */
:where(h1,h2,h3,h4,h5,h6) > b {
  color: hotpink;
}

/* in the middle */
article :is(header,footer) > p {
  color: gray;
}

/* at the end */
.dark-theme :where(button,a) {
  color: rebeccapurple;
}

/* multiple */
:is(.dark-theme, .dim-theme) :where(button,a) {
  color: rebeccapurple;
}

/* stacked */
:is(h1,h2):where(.hero,.subtitle) {
  text-transform: uppercase;
}

/* nested */
.hero:is(h1,h2,:is(.header,.boldest)) {
  font-weight: 900;
}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容