Avoid the need for Javascript with a clever use of CSS pseudo selectors as demonstrated in a insightful article by Heydon Pickering. I highly recommend checking it out.
The nth-last-child(n+4)
selector targets elements that are at least 4 from the end. This technique allows you to select specific elements based on their position within the container.
Combining nth-last-child(n+4) ~ li
is key to achieving the desired effect. The sibling selector ~
selects elements that share the same parent and appear after the specified target element.
Update
In response to feedback, an additional CSS selector has been added to target elements numbering 3 or fewer. Simply adjust the value from -n+3
to 3
for this specific case.
Unless faced with a challenge or enjoy working with nth
child selectors, using CSS creatively can offer solutions that might otherwise seem reliant on Javascript.
li:nth-last-child(-n+3):first-child,
li:nth-last-child(-n+3):first-child ~ li {
/* Styling for 3 or Less */
color: blue;
}
li:nth-last-child(n+4),
li:nth-last-child(n+4) ~ li {
/* Styling for 4 or More */
color: red;
}
<ul>
<li>1</li>
<li>2</li>
</ul>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
</ul>