CSS CSS Selectors Advanced Selectors :nth-child

So confused with the MDN :nth-last-child() example?

<h4>A list of four items (styled):</h4>
<ol>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
</ol>

<h4>A list of two items (unstyled):</h4>
<ol>
  <li>One</li>
  <li>Two</li>
</ol>
/* If there are at least three list items,
   style them all */
li:nth-last-child(n+3),
li:nth-last-child(n+3) ~ li {
  color: red;
}

MDN nth-last-child() example. I get that 3 or more <li> will turn all <li> color red. Also it is using a general selector. However I still dont get how this work when breaking it down. Can some explain this to me please?

2 Answers

Dave StSomeWhere
Dave StSomeWhere
19,809 Points

Here's how I would break it down.

First I would mentally assign index values to the li elements (only the list of four items matters), like so:

<h4>A list of four items (styled):</h4>
<ol>
  <li>One</li>    <!-- nth-last-child index = 4 -->
  <li>Two</li>    <!-- nth-last-child index = 3 -->
  <li>Three</li>  <!-- nth-last-child index = 2 -->
  <li>Four</li>   <!-- nth-last-child index = 1 -->
</ol>

Next I would break up the CSS into two parts (separated by the comma) - basically it is functionally the same as:

li:nth-last-child(n+3) {
  color: red;
}

li:nth-last-child(n+3) ~ li {
  color: red;
}

Executing the first CSS rule will color One and Two to red since their index values are greater than or equal to 3 (the "n+3").

Now, if you just execute the second rule alone without the first rule, you would get Two, Three and Four in red only. This is because the general selector (tilde) selects the following siblings of the same parent - it will select three and four for index 3 and two, three and four for index 4.

So, since we have the comma, which combines the rules - all 4 are red.

Does that help?

hello dave, and thanks for your response. i think i get it now. so the first code targets index 3 and will always move upwards. whilst the second code targets index 2 and moves downwards. however both codes can never work if there is no index 3 to begin with. it does make sense right.