waisie li waisie li - 3 months ago 9
CSS Question

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.

Answer

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>