2

Color is not applied as per CSS on the 3rd row, using first child(div.multiple-alerts .normal:first-child span).

https://jsfiddle.net/Lh6cpzeb/

div.multiple-alerts .high:first-child span{ color: yellow; }

div.multiple-alerts .normal:first-child span{ color: yellow; }
<div class="multiple-alerts">
  <div class="cls high"><span>high</span></div>
  <div class="cls high"><span>high</span></div>
  <div class="cls normal"><span>normal</span></div>
  <div class="cls normal"><span>normal</span></div>
</div>
Rakesh
  • 31
  • 1
  • 3
  • wrong use of first-child. first-child represents the very first child of a parent. Not first child that has a particular class. Good answer here on this: https://stackoverflow.com/questions/2717480/css-selector-for-first-element-with-class – Robert Wade Nov 16 '17 at 22:49

2 Answers2

1

The CSS is being applied the correct way, but I think your understanding of how the rules work may be slightly off. You're selecting the first child of all divs with class multiple-alerts which also has the class of normal. Well, the first child of multiple-alerts does not have the class normal (at least in the snippet you included), so your selector matches exactly zero elements.

Now, you may be tempted to go for something like first-of-type, but that only applies to tags, not classes. So, here's a workaround that you might find useful:

Let's say the standard colour for these spans is black, we will set all the spans inside .normal with yellow colour, then override it for all but the first one, like so:

div.multiple-alerts .normal span {
  color: yellow;
}
div.multiple-alerts .normal ~ .normal span {
  color: black;
}

If you're not sure how this is working here, the ~ works similarly to the +, but is broader. The + can only match with the very next sibling, whereas the ~ can match with any succeeding sibling - i.e. after, but not before.

Michael Evans
  • 971
  • 1
  • 13
  • 30
1

:nth-child(i) selector will solve the problem

div.multiple-alerts .cls:nth-child(3) span{ color: yellow; }
satyajit rout
  • 1,623
  • 10
  • 20