:is()、:where() 和 :has() 伪元素是 CSS 中用于样式化元素的非常强大的工具。它们是在 CSS 选择器 Level 4 规范中引入的。它们允许我们将样式应用于符合特定条件的任何元素,例如元素的类型、元素的位置和元素的后代。
:is()
MDN解释::is() CSS 伪类函数以选择器列表作为参数,并选择该列表中任意一个选择器可以选择的元素。这对于以更紧凑的形式编写大型选择器非常有用。
:is() 伪类可以用于基于选择器的组合来定位元素。它将一系列选择器作为其参数,并在元素匹配任何选择器时返回 true。
比如:
你想要针对所有类名为 isRed 或 isPretty 的元素进行定位,可以使用:is()伪类
<style>
div:is(.isRed, .isRed) {
color: red;
}
div:is(.isPretty) {
color: pink;
}
</style>
<body>
<div class="isRed">
<p>red</p>
</div>
<div class="isRed">
<p>red</p>
</div>
<div class="isPretty">
<p>Pretty</p>
</div>
<div>
<span> Not Pretty </span>
</div>
:where()
MDN解释:where() CSS 伪类函数接受选择器列表作为它的参数,将会选择所有能被该选择器列表中任何一条规则选中的元素。
:where() 伪类可以根据条件来定位元素。它以条件作为参数,并在元素匹配条件时返回 true。
比如:
你想要定位所有类名以 xxx 开头的所有元素,可以使用 :where()伪类来实现:
<style>
div:is(.isRed, .isRed) {
color: red;
}
div:is(.isPretty) {
color: pink;
}
div:where([class^="bold"]) {
font-weight: bold;
font-size: 30px;
}
</style>
<body>
<div class="isRed">
<p>red</p>
</div>
<div class="boldText isRed">
<p>red</p>
</div>
<div class="isPretty bold">
<p>Pretty</p>
</div>
<div class="bold">
<span> Not Pretty </span>
</div>
:is()和:where()的区别
伪元素 :is() 和 :where() 看起来在做同样的事情。但是,伪元素 :is() 用于根据选择器列表匹配元素,而伪元素 :where() 则用于根据条件匹配元素。
- :where() 和 :is() 的不同之处在于,:where() 的优先级总是为 0,但是 :is() 的优先级是由它的选择器列表中优先级最高的选择器决定的。
:has()
- :has() 伪类可以用于基于后代元素来定位元素。它以选择器作为参数,并在元素具有与选择器匹配的后代时返回 true。
- :has() 伪类的优先级计算方法与 :is() 和 :not() 相同:以其参数中具体的选择器进行计算。
语法:
:has( <forgiving-relative-selector-list> )
比如
你想要定位所有包含元素的元素,可以使用 :has() 伪类来实现
<style>
div:is(.isRed, .isRed) {
color: red;
}
div:is(.isPretty) {
color: pink;
}
div:is(.isPretty):has(p) {
background-color: purple !important;
}
div:where([class^="bold"]):has(span) {
font-size: 30px;
}
div:where([class^="bold"]) {
font-size: 20px;
font-weight: bold;
}
</style>
<body>
<div class="isRed">
<p>red</p>
</div>
<div class="boldText isRed">
<p>red</p>
</div>
<div class="isPretty bold">
<p>Pretty</p>
</div>
<div class="bold">
<span> Not Pretty </span>
</div>
<style>
h1,
h2,
h3 {
margin: 0 0 1rem 0;
}
/* 第一个 :is() 伪类用于选择列表中的任何标题元素。第二个 :is() 伪类用于将相邻的兄弟选择器的列表作为参数传递给 :has() */
/* :has() 伪类用于选择任何一个紧跟 H2、H3 或 H4 的 H1、H2、H3 元素(使用 + 指示),并使用 CSS 规则来减少此类 H1、H2 或 H3 元素后的间距 */
:is(h1, h2, h3):has(+ :is(h2, h3, h4)) {
margin: 0 0 0.25rem 0;
}
/* :is(h1, h2, h3):has(+ h2, + h3, + h4) {
margin: 0 0 0.25rem 0;
} */
h1:has(+ h2) {
color: red;
}
</style>
<body>
<section>
<article>
<h1>Morning Times</h1>
<h2>Delivering you news every morning</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua.
</p>
</article>
<article>
<h1>Morning Times</h1>
<h2>Delivering you news every morning</h2>
<h3>8:00 am</h3>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua.
</p>
</article>
</section>
</body>