waisie li
waisie li

Reputation: 343

How do I remove the margin-bottom of a child in the last of a set of elements?

How do I remove the margin-bottom of the p in the last container element with .col-md-2?

p {
  margin: 0;
}
.col-md-2 p {
  margin-bottom: 15px;
}
<div class="col-md-2-wrap">
  <div class="col-md-2">
    <p>lorum ipsumlorum ipsumlorum ipsumlorum ipsumlorum ipsumlorum ipsum</p>
    <p>lorum ipsumlorum ipsum</p>
  </div>
  <div class="col-md-2">
    <p>lorum ipsum lorum ipsum lorum ipsum lorum ipsum</p>
    <p>lorum ipsumlorum ipsumlorum ipsumlorum ipsum</p>
  </div>
</div>

Should I use the nth-child or last-of-type selector? I can't figure out how to use either for my situation.

Upvotes: 0

Views: 208

Answers (3)

lluca
lluca

Reputation: 301

.col-md-2:last-child > p:last-child {
  margin-bottom: 0px;
}

Upvotes: 0

Tyler Roper
Tyler Roper

Reputation: 21672

Personally I would just add another rule to specify "The last p of the last col-md-2 should have 0 margin" like so:

p {
  margin: 0;
}

.col-md-2 p {
  margin-bottom: 15px;
}

.col-md-2:last-of-type p:last-child {
  margin-bottom: 0px;
}

If you didn't want to do this for one reason or another, you could do the following:

p {
  margin: 0;
}

.col-md-2:not(:last-of-type) p, .col-md-2:last-of-type p:not(:last-child) {
  margin-bottom: 15px;
}

This one has two parts:

  1. .col-md-2:not(:last-of-type) p applies the margin to all p's except the ones that occur in the last col-md-2

  2. .col-md-2:last-of-type p:not(:last-child) applies it to all p's of the last col-md-2 except the very last p.

Upvotes: 1

DaniP
DaniP

Reputation: 38252

You can use twice the last-child selector, try this:

.col-md-2-wrap div:last-child p:last-child {
  margin:0;
}
  • .col-md-2-wrap ... Target the wrapper.

  • div:last-child ... Target the last .col-md-2 inside wrapper

  • p:last-child ... Target the last p inside that last .col-md-2

.col-md-2-wrap {
  background: purple;
  color: white;
}
p {
  margin: 0;
}
.col-md-2 p {
  margin-bottom: 15px;
}
.next {
  background: gold;
  height: 50px;
}
.col-md-2-wrap div:last-child p:last-child {
  margin: 0;
}
<div class="col-md-2-wrap">
  <div class="col-md-2">
    <p>lorum ipsumlorum ipsumlorum ipsumlorum ipsumlorum ipsumlorum ipsum</p>
    <p>lorum ipsumlorum ipsum</p>
  </div>
  <div class="col-md-2">
    <p>lorum ipsum lorum ipsum lorum ipsum lorum ipsum</p>
    <p>lorum ipsumlorum ipsumlorum ipsumlorum ipsum</p>
  </div>
</div>
<div class="next"></div>

Upvotes: 0

Related Questions