0

Please check the below code. First style is perfectly applied but not the second one for "regular 1". I have to apply blue color on the first element with class "regular".

.plan-list .basic:first-child {
    background: red;
  }
  .plan-list .regular:first-child {
    background: blue;
  }
<ul class="plan-list">
  <li class="plan basic">basic 1</li>
  <li class="plan regular">regular 1</li>
  <li class="plan regular">regular 2</li>
  <li class="plan basic">basic 2</li>
</ul>
isherwood
  • 58,414
  • 16
  • 114
  • 157
user784187
  • 123
  • 1
  • 2
  • 9
  • 1
    You can't select elements by index inside a class selector. You'd need scripting (jQuery would make it easy). – isherwood Jul 17 '19 at 13:43
  • First apply your desired styles to all your elements with that class. Then "undo" the styles for elements with the class that come after the first one. .plan-list li.regular { background: blue; } .plan-list li.regular ~ .regular { background: transparent; } – Syam Mohan M P Jul 17 '19 at 14:09
  • @SyamMohan, yes thanks. – user784187 Jul 17 '19 at 14:12

3 Answers3

0

should be

<style>
  .plan-list .basic:first-child {
    background: red;
  }
  .plan-list .regular:nth-child(2) {
    background: blue;
  }
</style>

<ul class="plan-list">
  <li class="plan basic">basic 1</li>
  <li class="plan regular">regular 1</li>
  <li class="plan regular">regular 2</li>
  <li class="plan basic">basic 2</li>
</ul>

This is because, while this li is the first child WITH THAT CLASS, it is in fact, the second child within its parent

borbesaur
  • 681
  • 4
  • 10
  • 1
    This still targets elements by index, not by class and subindex. It probably can't be accomplished with CSS unless you rely on index. – isherwood Jul 17 '19 at 13:42
  • This is a good point. To target through subindex inside a parent you probably need some JS – borbesaur Jul 17 '19 at 13:45
0

When you set first-child it literally means it must be the first child of its parent.

So, you are trying to select an element with class regular AND that is the first child of its parent.

Azametzin
  • 5,223
  • 12
  • 28
  • 46
0

Just to add to other answers, from MDN documentation: The :first-child CSS pseudo-class represents the first element among a group of sibling elements.

robson3999
  • 25
  • 5