CSS 代码的使用案例

221 阅读1分钟

自从开发人员编写CSS代码以来,我们一直迫切希望有一种方法可以让父元素基于子元素的特征进行造型。 直到现在,这才成为可能。 CSS引入了:has 伪类,它允许根据相对的CSS选择器来确定父元素的样式。

让我们来看看CSS中:has 的几个使用案例。

/*
  If an `a` element contains an image, set the `a`'s display
*/
a:has(img) {
  display: block;
}

/*
  If a `figure` has a `caption` with a `multiline` class
  allow the `figure` to have any height
*/
figure {
  height: 200px;
}
figure:has(caption.multiline) {
  height: auto;
}

/*
  Hide an advert containing `div` until ads load
  and have been injected
*/
.ad-container {
  display: none;
}
.ad-container:has(.ad) {
  display: block;
}

/*
  If we have an `article` element without a heading,
  add top padding because `H1`s have top padding
*/
article:not(:has(h1)) {
  padding-top: 20px;
}

苹果的Safari是第一个支持:has 的浏览器,不过我们应该看到其他浏览器很快就会效仿,因为它是官方CSS规范的一部分。现在我们有了这个新的伪类,你认为你会经常使用它吗? 或者你会坚持使用你目前的变通方法?