Trying to understand css nth-of-type selector

I am trying to understand why this selector nth-of-typedoes not work as expected. My goal is to make the first element .rowred and the rest after the first blue, leaving the elements green as they are.

https://jsfiddle.net/darrengates/pa34zyjd/14/

.wrapper div {
  width: 200px;
  background-color: green;
  color: white;
  margin: 5px;
  padding: 5px;
}
.wrapper .row:nth-of-type(n+1) {
  background-color: red;
}
.wrapper .row:nth-of-type(n+2) {
  background-color: blue;
}
<div class="wrapper">
  <div class="option">option</div>
  <div class="button">some button</div>
  <div class="row">I wanna be red</div>
  <div class="row">I wanna be blue</div>
  <div class="row">I wanna be blue</div>
  <!-- all other row elements after the first should be blue -->
</div>
Run codeHide result
+4
source share
2 answers

The selector n-th-of-typerefers to the tag tag at the same level, not to the class, in this case tags divthat are siblings inside .wrapper. Therefore, you need this CSS, since they are there third and fourth div:

.wrapper .row:nth-of-type(n+3) {
  background-color: red;
}
.wrapper .row:nth-of-type(n+4) {
  background-color: blue;
}

https://jsfiddle.net/cb3qd8t6/

+3

nth-* , . ~ + :

.wrapper div {
  width: 200px;
  background-color: green;
  color: white;
  margin: 5px;
  padding: 5px;
}
.wrapper .row {
  background-color: red;
}
.wrapper .row ~ .row {
  background-color: blue;
}
<div class="wrapper">
  <div class="option">option</div>
  <div class="button">some button</div>
  <div class="row">I wanna be red</div>
  <div class="row">I wanna be blue</div>
  <div class="row">I wanna be blue</div>
  <!-- all other row elements after the first should be blue -->
</div>
Hide result
+2

Source: https://habr.com/ru/post/1669433/


All Articles