Css equivalent of :has() [duplicate]

半腔热情 提交于 2019-12-07 03:35:54

问题


In the following example:

<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;
}

If div .row is parent of div .section reset bottom margin to 0.

I can do this with jquery, but is there a way to do it in css?


回答1:


At the moment there is no way in CSS to select the parent element of another element.

However, in CSS4 there is the :has pseudo-class - http://dev.w3.org/csswg/selectors-4/ :has

the following selector matches only elements that contain an child:

a:has(> img)

The following selector matches a element immediately followed by another element:

dt:has(+ dt)

The following selector matches 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 element which contains anything that’s not a header element.

It looks like you may be using a recursive function to generate your sections/rows. Perhaps add a class to the row if it has sub-sections? Then you could target that class to apply margin-bottom to.




回答2:


You could do this by applying a negative margin to the .section element that's equivalent to the standard margin of .row element.

.row {
  margin-bottom: 20px;
}

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


来源:https://stackoverflow.com/questions/29037763/css-equivalent-of-has

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!