:where()
:where() CSS 偽類函式接受一個選擇器列表作為其引數,並選擇可被該列表中任一選擇器選中的任何元素。
:where() 和 :is() 的區別在於 :where() 始終具有 0 特異度,而 :is() 則採用其引數中最具體選擇器的特異度。
試一試
ol {
list-style-type: upper-alpha;
color: darkblue;
}
/* Not applied to ol, because of lower specificity */
:where(ol, ul, menu:unsupported) :where(ol, ul) {
color: green;
}
:where(ol, ul) :where(ol, ul) ol {
list-style-type: lower-greek;
color: chocolate;
}
<ol>
<li>Saturn</li>
<li>
<ul>
<li>Mimas</li>
<li>Enceladus</li>
<li>
<ol>
<li>Voyager</li>
<li>Cassini</li>
</ol>
</li>
<li>Tethys</li>
</ul>
</li>
<li>Uranus</li>
<li>
<ol>
<li>Titania</li>
<li>Oberon</li>
</ol>
</li>
</ol>
語法
:where(<complex-selector-list>) {
/* ... */
}
引數
:where() 偽類需要一個選擇器列表,即一個由一個或多個逗號分隔的選擇器組成的列表,作為其引數。該列表不得包含偽元素,但允許使用任何其他簡單選擇器、複合選擇器和複雜選擇器。
寬容選擇器解析
規範將 :is() 和 :where() 定義為接受寬容選擇器列表。
在 CSS 中使用選擇器列表時,如果任何選擇器無效,則整個列表被視為無效。而使用 :is() 或 :where() 時,如果其中一個選擇器未能解析,則不會將整個選擇器列表視為無效,而是忽略不正確或不受支援的選擇器,並使用其他選擇器。
:where(:valid, :unsupported) {
/* … */
}
即使在不支援 :unsupported 的瀏覽器中,也會正確解析並匹配 :valid,而
:valid,
:unsupported {
/* … */
}
即使支援 :valid,不支援 :unsupported 的瀏覽器也會忽略。
示例
比較 :where() 和 :is()
此示例演示了 :where() 的工作原理,並說明了 :where() 和 :is() 之間的區別。
以下面的 HTML 為例
<article>
<h2>:is()-styled links</h2>
<section class="is-styling">
<p>
Here is my main content. This
<a href="https://mozilla.org">contains a link</a>.
</p>
</section>
<aside class="is-styling">
<p>
Here is my aside content. This
<a href="https://mdn.club.tw">also contains a link</a>.
</p>
</aside>
<footer class="is-styling">
<p>
This is my footer, also containing
<a href="https://github.com/mdn">a link</a>.
</p>
</footer>
</article>
<article>
<h2>:where()-styled links</h2>
<section class="where-styling">
<p>
Here is my main content. This
<a href="https://mozilla.org">contains a link</a>.
</p>
</section>
<aside class="where-styling">
<p>
Here is my aside content. This
<a href="https://mdn.club.tw">also contains a link</a>.
</p>
</aside>
<footer class="where-styling">
<p>
This is my footer, also containing
<a href="https://github.com/mdn">a link</a>.
</p>
</footer>
</article>
在這個有些刻意的例子中,我們有兩個文章,每個文章都包含一個 section、一個 aside 和一個 footer。它們的不同之處在於用於標記子元素的類。
為了對連結進行分組選擇,同時保持 is-styling 和 where-styling 樣式清晰,我們可以按以下方式使用 :is() 或 :where()
html {
font-family: sans-serif;
font-size: 150%;
}
:is(section.is-styling, aside.is-styling, footer.is-styling) a {
color: red;
}
:where(section.where-styling, aside.where-styling, footer.where-styling) a {
color: orange;
}
然而,如果我們以後想使用由低特異性型別選擇器組成的複合選擇器來覆蓋頁尾中連結的顏色,該怎麼辦?
footer a {
color: blue;
}
這對於紅色連結不起作用,因為 :is() 內部的選擇器會計入整個選擇器的特異性,並且類選擇器比元素選擇器具有更高的特異性。
然而,:where() 內部的選擇器特異性為 0,因此橙色頁尾連結將被我們的僅型別複合選擇器覆蓋。
注意:您也可以在 GitHub 上找到此示例;請參閱 is-where。
規範
| 規範 |
|---|
| 選擇器 Level 4 # 零匹配 |
瀏覽器相容性
載入中…