CSS 现在包含一个 :has 选择器,它允许我们根据元素内部发生的情况应用样式。通常被称为父选择器, :has() 函数允许我们实现这一点以及更多。
让我们来看看这个相对选择器。
div:has(img) {
background: black;
}
如果 div 中有图像,它只会应用背景,否则不会。所以
<div>
<img></img>
</div>
将被选中,但如果它是一个简单的 div,或者其中有任何其他内容,则样式将不会应用于它们。
链接
我们甚至可以链接选择器并嵌套条件:
div:has(h2):has(ul) {
background: black;
}
不仅仅是父选择器,您也可以通过将其与父级选择器组合来选择子级。
/* Matches <figure> elements that have a <figcaption> as a child element */
figure:has(figcaption) { … }
/* Matches <img> elements that is a child of a <figure> that contains a <figcaption> child element */
figure:has(figcaption) img { … }
第二个选择器让我们能够选择子图像,我们可以获得更多的创意,它打开了一个充满机遇的世界。