1

I've got the following HTML structure which I'm trying to style using CSS selectors only:

<footer>
  <div class="row">
    <div class="col-md-3"></div>
    <nav class="col-md-9"></nav>
  </div>

  <div class="row">
    <div class="col-md-3"></div>
    <div class="col-md-9"></div>
  </div>
</footer>

Imagine all the columns are stacked in a small viewport. I want all columns except for the very last one to apply a margin-bottom to space the columns.

I've tried some different approaches, but to no avail:

footer [class^="col-"]:not(:last-child) {
  margin-bottom: 3rem;
}

footer [class^="col-"]:not(:last-of-type) {
  margin-bottom: 3rem;
}

First, why do these fail? Second, what's the right approach here?

3
  • :not cannot handle complex selectors. stackoverflow.com/a/26997609/2813224 Commented Mar 17, 2017 at 22:25
  • @zer00ne: There aren't any complex selectors in use here. There's just one pseudo-class per :not() here. Commented Mar 18, 2017 at 4:18
  • 1
    "First, why do these fail?" They do work - they're just matching too many elements. Every last column is the last child of its parent row. That's the reason why. Commented Mar 18, 2017 at 4:20

2 Answers 2

2

First use footer > div.row > * to apply the margin-bottom 3rem, then use footer > div:last-child > div:last-child ( or footer > div.row:last-child > div:last-child, won't make a difference) to reset the last margin to 0:

(note: I only used the .wrap div to apply a backgroun in order to make the margins (and the "no-margin" on the last element) visible)

.wrap {
background: #ccc;
}
footer > div.row > * {
margin-bottom: 3rem;
background: #dff;
}
footer > div:last-child > div:last-child {
margin-bottom: 0rem;
}
<div class="wrap">
<footer>
  <div class="row">
    <div class="col-md-3">Content 1</div>
    <nav class="col-md-9">Content 2</nav>
  </div>

  <div class="row">
    <div class="col-md-3">Content 3</div>
    <div class="col-md-9">Content 4</div>
  </div>
</footer>
</div>

Sign up to request clarification or add additional context in comments.

Comments

1

I would suggest styling them all, then removing the margin on the last one, like so:

footer [class^="col-"] {
    margin-bottom: 3rem;
}

footer .row:last-child [class^="col-"]:last-child {
    margin-bottom: 0; // or however much
}

If using last-of-typeis beneficial in any way, then by all means use that, but it should be equivalent if you're implementing Bootstrap (which your class names suggest).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.