IN BRIEF:
Identify and style the last two elements with the same class that are adjacent to each other.
To achieve this effect, use the following CSS selector:
.a:nth-last-child(2),
.a:nth-last-child(2) + .a {
...
}
A demonstration showcasing the selector in action is provided below with two unordered lists. Note how only the first list is affected due to having two adjacent elements of the same class at the end.
.a:nth-last-child(2),
.a:nth-last-child(2) + .a {
color: blue;
background: #cce5ff;
}
<ul>
<li class="a">One</li>
<li class="a">Two</li>
<li class="a">Three</li>
<li>Four</li>
<li>Five</li>
<li class="a">Six</li>
<li class="a">Seven</li>
</ul>
<ul>
<li class="a">One</li>
<li class="a">Two</li>
<li class="a">Three</li>
<li>Four</li>
<li>Five</li>
<li>Six</li>
<li class="a">Seven</li>
<li>Eight</li>
<li class="a">Nine</li>
</ul>
OTHER SELECTORS:
This selection targets the initial two elements sharing a class along with the adjoining final two elements within a parent container.
.a:nth-child(2),
.a:nth-child(3),
.a:nth-last-child(2),
.a:nth-last-child(2) + .a {
color: blue;
background: #cce5ff;
}
<ul>
<li class="a">One</li>
<li class="a">Two</li>
<li class="a">Three</li>
<li>Four</li>
<li>Five</li>
<li class="a">Six</li>
<li class="a">Seven</li>
</ul>
<ul>
<li class="a">One</li>
<li class="a">Two</li>
<li class="a">Three</li>
<li>Four</li>
<li>Five</li>
<li>Six</li>
<li>Seven</li>
<li class="a">Eight</li>
<li class="a">Nine</li>
</ul>
Selects all instances of the specified class, excluding the first occurrence, within a parent container.
.a:not(:first-child) {
color: blue;
background: #cce5ff;
}
/*
Functions equivalently to .a:not(:first-child)
*/
.a:not(:nth-child(1)) {
font-weight: bold;
}
<ul>
<li class="a">One</li>
<li class="a">Two</li>
<li class="a">Three</li>
<li>Four</li>
<li>Five</li>
<li class="a">Six</li>
<li class="a">Seven</li>
</ul>
<ul>
<li class="a">One</li>
<li class="a">Two</li>
<li class="a">Three</li>
<li>Four</li>
<li>Five</li>
<li>Six</li>
<li>Seven</li>
<li class="a">Eight</li>
<li class="a">Nine</li>
</ul>
Targets the second, third, sixth, and seventh occurrences of the designated class when their child node matches that of the selector. (Note: This does not have the desired effect on the second unordered list)
.a:nth-child(2),
.a:nth-child(3),
.a:nth-child(6),
.a:nth-child(7) {
color: blue;
background: #cce5ff;
}
<ul>
<li class="a">One</li>
<li class="a">Two</li>
<li class="a">Three</li>
<li>Four</li>
<li>Five</li>
<li class="a">Six</li>
<li class="a">Seven</li>
</ul>
<ul>
<li class="a">One</li>
<li class="a">Two</li>
<li class="a">Three</li>
<li>Four</li>
<li>Five</li>
<li>Six</li>
<li>Seven</li>
<li class="a">Eight</li>
<li class="a">Nine</li>
</ul>