CSS :is()、:where()、:has() 和 :not() HTML - CSS -

2025-06-07

CSS :is()、:where()、:has() 和 :not()

HTML -

CSS -

大家好,今天我将讨论一些新的 Css 伪类选择器

注意 - 在使用这些选择器之前,请先在https://caniuse.com/查看它们的浏览器支持情况

让我们开始吧...

HTML -

<div class="parent">
<p class="element1">Element 1</p>
<p class="element2">Element 2</p>
<p class="element3">Element 3</p>
<p class="element4">Element 4</p>
</div>
Enter fullscreen mode Exit fullscreen mode

CSS -

  • :is() - 有时你必须为多个元素提供相同的样式,所以你可以这样做
.element1,.element2,.element3,.element4{
color:red;
}
Enter fullscreen mode Exit fullscreen mode

它会创建一个链接,有时可能足够长,但使用 :is() 选择器,现在你可以像这样

:is(.element1,.element2,.element3,.element4){
color:red;
}

//if the element has a parent then do it like this
.parent :is(.element1,.element2,.element3,.element4){
color:red;
}
Enter fullscreen mode Exit fullscreen mode

注意 - 如果像上面那样将 :is() 选择器与父元素一起使用,请记住在 :is() 选择器前始终留一个空格。

  • :where() - 此选择器与 :is() 工作原理相同,不同之处在于特异性,:is() 会采用组中特异性最高的元素的特异性,而 :where() 无论将多少个元素组合在一起,其特异性均为 0
.parent :where(.element1,.element2,.element3,.element4){
  color:red
}
Enter fullscreen mode Exit fullscreen mode

注意 - 如果像上面那样将 :where() 选择器与父元素一起使用,请记住在 :where() 选择器前始终留一个空格。

  • :has() - 此选择器仅使用其 class、Id、tagName 等检查某些元素是否存在。
<div class="parent">
  <input type="checkbox" />
  <p>Child</p>
</div>
Enter fullscreen mode Exit fullscreen mode
.parent:has([type="checkbox"]:checked) p{
  color:red
}
Enter fullscreen mode Exit fullscreen mode

它将检查父元素是否具有复选框类型的输入并且是否被选中,如果被选中,则 p 标签的颜色将为红色,否则将为默认的黑色。

注意 - 如果是 :has() 则不需要在它前面添加空格,你可以在上面的例子中看到它

  • :not() - 此选择器用于设置除 :not() 参数内的元素之外的所有元素的样式
// Inside the parent element it will provide the color red to all p elements except the last child or last p element inside that parent element
.parent :not(p:nth-last-child(1)){
  color:red;
}
Enter fullscreen mode Exit fullscreen mode

注意 - 如果像上面那样将 :not() 选择器与父元素一起使用,请记住在 :not() 选择器前始终留一个空格。

感谢您查看此帖子

您可以通过以下方式联系我 -
Instagram - https://www.instagram.com/supremacism__shubh/
LinkedIn - https://www.linkedin.com/in/shubham-tiwari-b7544b193/
电子邮件 - shubhmtiwri00@gmail.com

^^您可以通过以下链接捐款来帮助我谢谢👇👇 ^^
☕ --> https://www.buymeacoffee.com/waaduheck <--

另请查看这些帖子
https://dev.to/shubhamtiwari909/js-push-and-pop-with-arrays-33a2/edit

https://dev.to/shubhamtiwari909/tostring-in-js-27b

https://dev.to/shubhamtiwari909/join-in-javascript-4050

https://dev.to/shubhamtiwari909/going-deep-in-array-sort-js-2n90

文章来源:https://dev.to/shubhamtiwari909/css-iswherehas-and-not-2afd
PREV
JWT(JSON Web Token) JWT 用于什么?
NEXT
React 中的延迟加载图像