CSS 伪类函数 :where() 接受一个选择器列表作为输入,并选择与该列表中的任何选择器匹配的每个元素。
语法
:where(<complex-selector-list>) {
/* css declarations */
}
CSS :where() 示例
以下示例演示了 伪类 :where() 的用法。
<html>
<head>
<style>
main :where(h1, h2, h3) {
color: rgb(102, 0, 255);
}
:where(h2) {
text-decoration-line: underline;
}
div {
border: 3px solid black;
}
</style>
</head>
<body>
<main>
<h1>Heading 1</h1>
<h3>Heading 3</h3>
<div>
<h2>Heading 2</h2>
<p>Paragraph under div</p>
</div>
</main>
</body>
</html>
:where() 和 :is() 之间的区别
:where() 和 :is() 之间的区别在于它们的特殊行为,如下所示:
:where() | :is() |
---|---|
它是一个 CSS 选择器,允许您在不增加特异性的情况下对选择器进行分组。 | 它是一个 CSS 选择器,允许您对选择器进行分组,但与 :where() 不同的是,它在其括号内继承了最具体的选择器的特殊性 |
它充当一个容器,您可以在其中编写复杂的选择器,而不会影响这些选择器的特异性。 | 它仅在需要时用于增加特异性,同时保持单个选择子的特异性 |
例如,:where(div, p) { /* styles */ } 在不增加特异性的情况下对 div 和 p 选择器进行分组。 | 例如,:is(div, p) { /* styles */ } 将采用 div 或 p 的特异性,以更具体者为准。 |
总之, :where() 保持特异性为 0,而 :is() 根据括号内最特异性的选择器调整其特异性。
例- 此示例演示了如何将 :is() 用于特定样式。
- :where() 可用于添加其他样式,而无需更改 :is() 设置的特异性或覆盖样式。
- 保留了 .special-box 元素的特定样式,并使用 :where() 添加了其他样式。
<html>
<head>
<style>
:is(.box, .special-box) {
background-color: lightgray;
color: black;
font-weight: bold;
}
:where(.box, .special-box) {
border: 2px solid black;
padding: 10px;
margin: 10px;
}
:is(.special-box) {
background-color: blue;
color: white;
}
:where(.special-box) {
font-style: italic;
}
</style>
</head>
<body>
<div class="container">
<div class="box">Box A</div>
<div class="special-box">Special Box</div>
<div class="box">Box B</div>
</div>
</body>
</html>
宽容选择器解析
在 CSS 中原谅选择器解析的概念是指 :is() 和 :where() 选择器如何处理选择器列表中的无效选择器。
在 CSS 中,如果选择器列表中的选择器无效,则整个列表将被视为无效,并且不会应用与之关联的样式。
使用 :is() 和 :where(),列表中不正确或不受支持的选择器将被忽略,其余有效的选择器仍将应用。换句话说,:is() 和 :where() 提供了一种宽容机制,其中单个无效的选择器不会破坏整个选择器列表。
例在以下示例中:
- :is() 和 :where() 选择器用于设置特定元素的样式。
- 特殊样式应用于 .content div 中类为 .special 的框。
- .container div 中的标头具有独特的样式,忽略了无效的选择器。
- .container 内的所有框都使用通用样式。
- .container 内的 .footer 中的段落的样式不同。
- :where(.box.invalid-selector) 中的无效选择器不会破坏整个规则,这表明了对选择器解析的宽容。
<html>
<head>
<style>
:where(.content) :is(.box.special) {
background-color: yellow;
color: black;
font-weight: bold;
}
:where(.container) :where(.header, .invalid-selector) {
background-color: lightblue;
color: white;
}
:where(.container) :is(.box) {
border: 2px solid black;
margin: 10px;
padding: 10px;
}
:where(.container) :where(.footer) p {
font-style: italic;
color: gray;
}
:where(.container) :where(.box.invalid-selector) {
text-decoration: underline;
}
</style>
</head>
<body>
<div class="container">
<div class="header">
<h1>Main Heading</h1>
</div>
<div class="content">
<div class="box">Box 1</div>
<div class="box special">Special Box</div>
<div class="box">Box 3</div>
</div>
<div class="footer">
<p>Footer Content</p>
</div>
</div>
</body>
</html>