CSS :has() 伪类表示一个元素,该元素基于它是否具有与某个选择器匹配的子元素。
语法
:has(<relative-selector-list>) {
/* ... */
}
Firefox 浏览器不支持 :has() 伪类。
要记住的 Ponits
- 当浏览器不支持 :has() 伪类时,只有在 :is() 或 :where() 选择器中使用 :has() 时,整个选择器块才会起作用。
- 你不能在另一个 :has() 选择器中使用 :has() 选择器,因为许多伪元素的存在基于其父元素的样式设置。允许您使用 :has() 选择这些伪元素可能会导致循环查询。
- 伪元素不能用作 :has() 伪类中的选择器或锚点。
CSS :has() - 同级组合器
这是一个如何使用 :has() 函数选择所有紧跟 h3 元素的 h2 元素的示例 -
<html>
<head>
<style>
div {
background-color: pink;
}
h2:has(+ h3) {
margin: 0 0 50px 0;
}
</style>
</head>
<body>
<p>You can see it adds bottom margin to h2 elements immediately followed by an h3 element.</p>
<div>
<h2>QikepuCom</h2>
<h3>CSS Pseudo-class - :has()</h3>
<p>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old.</p>
</div>
</body>
</html>
CSS :has() - 使用 :is() 伪类
CSS 选择器 :is(h1, h2, h3) 选择所有 h1、h2 和 h3 元素。然后, :has() 伪类选择这些元素中的任何一个,这些元素具有 h2、h3 或 h5 元素作为它们的下一个同级元素,如下所示 -
<html>
<head>
<style>
div {
background-color: pink;
}
:is(h1, h2, h3):has(+ :is(h2, h3, h5)) {
margin-bottom: 50px ;
}
</style>
</head>
<body>
<p>You can see it adds bottom margin to h2 elements immediately followed by an h3 element and h3 element followed by immediately h4.</p>
<div>
<h2>QikepuCom</h2>
<h3>CSS Pseudo-class :has()</h3>
<h5>with :is() Pseudo-class</h5>
<p>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old.</p>
</div>
</body>
</html>
CSS :has() - 逻辑运算
- :has(video, audio) 选择器检查元素中是否存在视频或音频元素。
- :has(video):has(audio) 选择器检查元素是否包含视频或音频元素。
这是一个如何使用 :has() 伪类为正文元素添加红色边框和 50% 宽度的示例,如果它包含视频或音频元素 -
<html>
<head>
<style>
video {
width: 50%;
margin: 50px;
}
body:has(video, audio) {
border: 3px solid red;
}
</style>
</head>
<body>
<video controls src="images/boat_video.mp4"></video>
</body>
</html>
正则表达式和 :has() 类比
CSS :has() 选择器和带有 lookahead 断言的正则表达式有一个相似之处,它们使您能够根据特定模式定位元素(或字符串),而无需实际选择与该模式匹配的元素(或字符串)。
特征 | 描述 |
---|---|
Positive lookahead (?=pattern) | CSS 选择器和正则表达式 abc(?=xyz) 都允许您根据紧随其后的另一个元素的存在来选择元素,而无需实际选择另一个元素本身。 |
Negative lookahead (?!pattern) | CSS选择器.abc:has(+ :not(.xyz))类似于正则表达式abc(?!xyz)。仅当后面没有 .xyz 时,两者都选择 .abc。 |