Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Css equivalent of :has() [duplicate]

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?

like image 398
user3176519 Avatar asked Mar 13 '15 16:03

user3176519


People also ask

Can I use CSS has ()?

Presently, the CSS :has() selector is not widely supported by browsers; this selector only works in the latest version of Safari or via the experimental features flag in the latest version of Chrome. So for now, we must not use :has() in production.

How do I target a sibling in CSS?

Adjacent Sibling Selector (+) The adjacent sibling selector is used to select an element that is directly after another specific element. Sibling elements must have the same parent element, and "adjacent" means "immediately following".

How do you target a parent element in CSS?

The element>element selector is used to select elements with a specific parent. Note: Elements that are not directly a child of the specified parent, are not selected.

Has selector in sass?

The :has() CSS pseudo-class represents an element if any of the selectors passed as parameters (relative to the :scope of the given element), match at least one element. The :has() pseudo-class takes a selector list as an argument.


2 Answers

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 <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.

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.

like image 154
Richard Parnaby-King Avatar answered Oct 18 '22 18:10

Richard Parnaby-King


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;
}
like image 29
Chris Herbert Avatar answered Oct 18 '22 17:10

Chris Herbert