:has()的CSS等效选择器是什么?

20
在以下示例中:
<div class="section">
  <div class="row">...</div>
  <div class="row"> <!-- bottom margin here needs to be 0 -->
    <div class="section">
      <div class="row">...</div>
      <div class="row">...</div>
    </div>
  </div>
</div>

.row {
  margin-bottom:10px;
}

如果 div .row 是 div .section 的父元素,则将底部边距重置为 0。

我可以使用 JQuery 完成这个操作,但是否有一种方法可以使用 CSS 实现?


8
不,CSS没有父级选择器。 - Paul Roub
只是想澄清一下,您指向的 div 的底边距实际上会添加到 div 块的底部。这是您想要消除的空间吗? - j08691
1
为什么不使用像 .row:last-child { margin-bottom:0px;} 这样的东西?CSS不能向上,只能向下,因此是“级联”的一部分。 - Nick R
@Nick R:术语“级联”完全指的是其他事情,与父->子无关。 - BoltClock
2个回答

19

目前在CSS中,没有一种方式可以选择另一个元素的父元素。

然而,在CSS4中有:has伪类 - http://dev.w3.org/csswg/selectors-4/ :has

the following selector matches only <a> elements that contain an <img> child:

a:has(> img)

The following selector matches a <dt> element immediately followed by another <dt> element:

dt:has(+ dt)

The following selector matches <section> elements that don’t contain any heading elements:

section:not(:has(h1, h2, h3, h4, h5, h6))

Note that ordering matters in the above selector. Swapping the nesting of the two pseudo-classes, like:

section:has(:not(h1, h2, h3, h4, h5, h6))

...would result matching any <section> element which contains anything that’s not a header element.

看起来你可能正在使用递归函数生成你的部分/行。也许给行添加一个类,如果它有子部分的话?然后你可以针对该类应用 margin-bottom。


5
你混淆了CSS选择器和CSS。目前尚未确定:has()选择器是否可用于CSS。请参阅你所链接文档中的快速/完整配置文件部分。 - BoltClock
7
:has() 仍然不受支持。详见 https://developer.mozilla.org/en-US/docs/Web/CSS/:has 。 - Aleks Grunwald
2
只是一点小提示。CSS4并不存在,也永远不会存在。它只是具有选择器级别4的常规CSS :) - https://css-tricks.com/css4/ - Ronald

11

您可以通过对 .section 元素应用等于 .row 元素标准 margin 的负 margin 来实现此目的。

.row {
  margin-bottom: 20px;
}

.row > .section {
  margin-top: -20px;
}

4
并非所有情况下均有效。 - Lucas Vazquez

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接