CSS技巧::is()、 :where()、:has()伪元素的运用

:is()、:where() 和 :has() 伪元素是 CSS 中用于样式化元素的非常强大的工具。是在 CSS 选择器 Level 4 规范中引入的。允许将样式应用于符合特定条件的任何元素,例如元素的类型、元素的位置和元素的后代。

:is()

:is() 伪类可以用于基于选择器的组合来定位元素。它将一系列选择器作为其参数,并在元素匹配任何选择器时返回 true。

div:is(.isPink, .isPretty) {
  color: pink;
}

"isPink">

Pink

"isPretty">

Pretty

Not Pretty

:where()

:where() 伪类可以根据条件来定位元素。它以条件作为参数,并在元素匹配条件时返回 true。
例如,如果想要定位所有类名以 bold 开头的元素,可以使用 :where()伪类来实现:
将以下伪类添加到上述CSS文件中,将导致任何具有以 bold 开头的CSS类的子元素渲染为粗体。

div:where([class^="bold"]) {
  font-weight: bold;
}

<div class="isPink">
  <p>
    Pink
  p>
div>

<div  class="bold_text isPretty">
  <p>
    Pretty
  p>
div>


伪元素 :is() 和 :where() 看起来在做同样的事情。但是,伪元素 :is() 用于根据选择器列表匹配元素,而伪元素 :where() 则用于根据条件匹配元素。

:has()

:has() 伪类可以用于基于后代元素来定位元素。它以选择器作为参数,并在元素具有与选择器匹配的后代时返回 true。
例如,如果想要定位所有包含元素的元素,可以使用 :has() 伪类来实现。

div:has(p) {
  background-color: purple !important;
}

你可能感兴趣的:(css,前端)