提升CSS技巧::is(), :where(), 和:has()伪元素的运用
:is()、:where() 和 :has() 伪元素是 CSS 中用于样式化元素的非常强大的工具。它们是在 CSS 选择器 Level 4 规范中引入的。它们允许我们将样式应用于符合特定条件的任何元素,例如元素的类型、元素的位置和元素的后代。
:is()
:is() 伪类可以用于基于选择器的组合来定位元素。它将一系列选择器作为其参数,并在元素匹配任何选择器时返回 true。
例如,如果你想要针对所有类名为 isPink 或 isPretty 的元素进行定位,可以使用:is()伪类。
HTML/CSS
div:is(.isPink, .isPretty) {
color: pink;
}
<div class="isPink">
<p>
Pink
</p>
</div>
<div class="isPretty">
<p>
Pretty
</p>
</div>
<div>
<span>
Not Pretty
</span>
</div>
在浏览器中渲染时会看起来像这样:

2. :where()
:where() 伪类可以根据条件来定位元素。它以条件作为参数,并在元素匹配条件时返回 true。
例如,如果你想要定位所有类名以 bold 开头的元素,可以使用 :where()伪类来实现:
将以下伪类添加到上述CSS文件中,将导致任何具有以 bold 开头的CSS类的子元素渲染为粗体。
div:where([class^="bold"]) {
font-weight: bold;
}
HTML
<div class="isPink">
<p>
Pink
</p>
</div>
<div class="bold_text isPretty">
<p>
Pretty
</p>
</div>
在浏览器中渲染时会看起来像这样:

伪元素 :is() 和 :where() 看起来在做同样的事情。但是,伪元素 :is() 用于根据选择器列表匹配元素,而伪元素 :where() 则用于根据条件匹配元素。
3. :has()
:has() 伪类可以用于基于后代元素来定位元素。它以选择器作为参数,并在元素具有与选择器匹配的后代时返回 true。
例如,如果你想要定位所有包含元素的元素,可以使用 :has() 伪类来实现。在这一步中,我们的 HTML 没有任何变化。这个 CSS 的添加使得元素具有紫色的背景。
div:has(p) {
background-color: purple !important;
}
这是我们网页现在的样子:

这些新的伪元素是任何CSS技能集中不可或缺的工具。经过一些练习,你将能够自信地在自己的项目中使用它们。