0

I'm trying to apply some styles to some divs using nth-child.

I have a misunderstanding about how those nth-child are working.

In CSS the hierarchy will be: ID, class, pseudo-classes but in my example the class is somehow ignored.

I have a parent div that have inside 7 children divs. First 3 children divs have a class kid1, the next 4 divs have a class called kid2.

.parent {
  border: 1px solid orangered;
  display: flex;
  flex-flow: row nowrap;
  height: 200px;
  width: 80%;
}

.kid1 {
  padding: 20px;
}

.kid1:nth-child(1) {
  background: lime
}

.kid1:nth-child(2) {
  background: blue
}

.kid1:nth-child(3) {
  background: yellow
}

.kid2 {
  padding: 20px;
}

.kid2:nth-child(1) {
  background: orange
}

/*is counting starting with first element of the parent*/

.kid2:nth-child(4) {
  background: red
}

.kid2:nth-child(3) {
  background: red
}

.kid2:nth-child(4) {
  background: cyan
}
<div class="parent">
  <div class="kid1">FIRST</div>
  <div class="kid1">FIRST</div>
  <div class="kid1">FIRST</div>

  <div class="kid2">SECOND</div>
  <div class="kid2">SECOND</div>
  <div class="kid2">SECOND</div>
  <div class="kid2"></div>
</div>

The very strange part is on kid2 children divs because instead of starting counting from that class is start counting from verify first element and that will be kid1. Doesn't anybody know wth is acting like that?

https://jsfiddle.net/twu75ax1/

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
BurebistaRuler
  • 6,209
  • 11
  • 48
  • 66
  • because `.kid2:nth-child(1)` matches an element which is both `.kid2` and the `first-child` of its parent. And with the code provided this is not matching any element, while your _first_ `.kid2` element is actually matched by `.kid2:nth-child(4)`. – Fabrizio Calderan May 24 '19 at 07:54
  • I think you can read more on this, https://stackoverflow.com/questions/5428676/nth-child-doesnt-respond-to-class , what you're trying to achieve cannot be done with `:nth-child` and need another approach by using class – Duc Hong May 24 '19 at 07:57
  • @fcalderan I know that but I want to understand the loggic behaind this. – BurebistaRuler May 24 '19 at 08:06
  • The accepted answer to [this question](https://stackoverflow.com/questions/5545649/can-i-combine-nth-child-or-nth-of-type-with-an-arbitrary-selector) should solve any doubt – Christian Vincenzo Traina May 24 '19 at 08:19

0 Answers0