4

I want to select the last of every class type. I don't know how many list items are present, so I can't use nth-child(2) for example. Can I make this in css or do I have to add a last class width scripts?

  • group-1
  • group-1


  • group-2

  • group-2


  • group-3

  • group-3

.group-1:last-of-type {
  margin-bottom: 50px;
}
.group-2:last-of-type {
  margin-bottom: 50px;
}
.group-3:last-of-type {
  margin-bottom: 50px;
}
<ul>
  <li class="group-1">Group1</li>
  <li class="group-1">Group1</li>
  <li class="group-2">Group2</li>
  <li class="group-2">Group2</li>
  <li class="group-3">Group3</li>
  <li class="group-3">Group3</li>
</ul>
Jesse
  • 3,522
  • 6
  • 25
  • 40

2 Answers2

1

You can use adjacent sibling combinator + css selector.

element1 + element2 means it will select the second element element2 only if it immediately follows the first element element1.

Stack Snippet

.group-1+.group-2 {
  margin-top: 50px;
}

.group-2+.group-3 {
  margin-top: 50px;
}
<ul>
  <li class="group-1">Group1</li>
  <li class="group-1">Group1</li>
  <li class="group-1">Group1</li>
  <li class="group-2">Group2</li>
  <li class="group-2">Group2</li>
  <li class="group-2">Group2</li>
  <li class="group-2">Group2</li>
  <li class="group-2">Group2</li>
  <li class="group-2">Group2</li>
  <li class="group-3">Group3</li>
  <li class="group-3">Group3</li>
  <li class="group-3">Group3</li>
  <li class="group-3">Group3</li>
  <li class="group-3">Group3</li>
</ul>

Reference Link adjacent sibling combinator

Bhuwan
  • 16,525
  • 5
  • 34
  • 57
  • 1
    Good trick when we have to deal with margin, but it become more tricky if we have to set a color to last one for example :) – Temani Afif Jan 18 '18 at 09:27
  • @TemaniAfif yeah you are right. If want to change styling to last element we can use jQeury `last()` method. – Bhuwan Jan 18 '18 at 09:43
  • yes sure, with jQuery is easy ;) but we always have this philosophic non-ending question : "how to do it with pure CSS ?" :) – Temani Afif Jan 18 '18 at 09:47
-2

You can use: :nth-child(2n) in css

li:nth-child(2n){
  margin-bottom: 50px;
}
Bhuwan
  • 16,525
  • 5
  • 34
  • 57
  • "I don't know how many list items that are comming, so I can't use nth-child(2) for example." – Jesse Jan 18 '18 at 09:02
  • So please see this link [Last Item in class css](https://stackoverflow.com/questions/6401268/how-do-i-select-the-last-child-with-a-specific-class-name-in-css) it will help you – Alaa Obeidat Jan 18 '18 at 09:05