16

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?

Josh Crozier
  • 202,159
  • 50
  • 343
  • 273
user3176519
  • 353
  • 1
  • 4
  • 15
  • 8
    No, CSS does not have parent selectors. – Paul Roub Mar 13 '15 at 16:53
  • Just to clarify, the bottom margin of the div you point to actually adds space to the very bottom of your block of divs. That's the space you want to eliminate? – j08691 Mar 13 '15 at 16:54
  • Why not use something like `.row:last-child { margin-bottom:0px;}` CSS can't go up, only down, hence the `cascading` part. – Nick R Mar 13 '15 at 16:57
  • @Nick R: The term "cascading" refers to something else entirely. Nothing to do with parent -> child. – BoltClock Mar 13 '15 at 18:08

2 Answers2

17

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.

geisterfurz007
  • 3,390
  • 5
  • 29
  • 46
Richard Parnaby-King
  • 13,858
  • 11
  • 64
  • 123
  • 4
    You are conflating CSS selectors with CSS. It's still undecided if the `:has()` selector will be available in CSS. See the section on fast/complete profiles in the document you link to. – BoltClock Mar 13 '15 at 18:09
  • 3
    `:has()` is still not supported https://developer.mozilla.org/en-US/docs/Web/CSS/:has – Aleks Grunwald Oct 27 '20 at 12:47
8

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;
}
Sunil Garg
  • 10,122
  • 12
  • 92
  • 133
Chris Herbert
  • 5,577
  • 3
  • 17
  • 30