How to add style to second-to-last only if total number of children are even?

So, I have a dynamic number of list items and I would like to apply a style to the second to last…. IF only there are an even number of elements.

<ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
</ul>

I want to apply style to the Three li element in the above case, but nothing if as follows.

<ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
</ul>

solution

You could combine :nth-child(odd) and :nth-last-child(2).

This works because :nth-last-child(2) will select the second to last child, and :nth-child(odd) only selects it if it’s odd. If the total number of children is even, then the second to last child will always be odd.

ul li:nth-child(odd):nth-last-child(2) {
  color: #f00;
}
<ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
  <li>Four</li>
</ul>


<ul>
  <li>One</li>
  <li>Two</li>
  <li>Three</li>
</ul>