imbondbaby
imbondbaby

Reputation: 6411

Add padding to all childs except last

I am trying to add padding to all child elements of a div except the last one.

I tried using the negation for last-child but it doesn't even add padding to the rest of the child elements when I use that...

Here is my HTML:

#container .description:not(:last-child) {
  padding-bottom: 10px;
}
<div id="container">
  <h3>Title</h3>
  <div class="box">
    <div class="title">Description</div>
    <div class="description">Description 1</div>
  </div>
  <div class="box">
    <div class="title">Description</div>
    <div class="description">Description 2</div>
  </div>
  <div class="box">
    <div class="title">Description</div>
    <div class="description">Description 2</div>
  </div>
  Testing here
</div>

JSFiddle Demo

Upvotes: 4

Views: 8129

Answers (3)

dippas
dippas

Reputation: 60563

What about using :last-child instead, it is simple, and doesn't need to use the negation selector :not(which has less support than :first/last-child).

#container .box:last-child{
  padding-bottom: 0;
}

snippet

#container {
  border: 1px solid
}

#container .box {
  padding-bottom: 10px
}

#container .box:last-child {
  padding-bottom: 0;
}
<div id="container">
  <h3>Title</h3>
  <div class="box">
    <div class="title">Description</div>
    <div class="description">Description 1</div>
  </div>
  <div class="box">
    <div class="title">Description</div>
    <div class="description">Description 2</div>
  </div>
  <div class="box">
    <div class="title">Description</div>
    <div class="description">Description 2</div>
  </div>
  Testing here
</div>

Upvotes: 2

David Thomas
David Thomas

Reputation: 253318

You presumably want:

#container .description {
    padding-bottom: 10px;
}

#container > :last-child .description {
    padding-bottom: 0;
}

As your selector is currently written:

#container .description:not(:last-child){
    padding-bottom:10px;
}

It fails to match any elements because all the .description elements are the last-child of their parent elements.

In response to comments, a needlessly complex (and limited cross-browser compatible) approach using the negation operator:

#container .box:not(:last-child) .description {
    padding-bottom: 10px;
}

Upvotes: 3

AlliterativeAlice
AlliterativeAlice

Reputation: 12577

The following rule should be what you're looking for. It will add 10px of padding to all descriptions except the one in the last .box element:

#container .box:not(:last-child) .description{
    padding-bottom:10px;
}

Example fiddle

Upvotes: 7

Related Questions