在編寫 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;
}