Select the last occurrence of an element in the whole document
We saw the selector for the first occurrence and here is the selector for the last occurrence.
.target { /* Update with what you want to select (class, tag, etc) */
&:nth-last-child(1 of &):not(:has(~ * &) *):not(:has(~ &) *):not(:has(~ * &)):not(:has(&)) {
/* your CSS here */
}
}
The above will select the element with the class .target
if:
- It's the last element among its siblings having the same class (
&:nth-last-child(1 of &)
) - It doesn't have a child with the same class (
:not(:has(&))
) - It's not the previous sibling of an element having a child with the same class (
:not(:has(~ * &))
) - It's not the child of an element that is the previous sibling of an element with the same class (
:not(:has(~ &) *)
) - It's not the child of an element that is the previous sibling of an element having a child with the same class (
:not(:has(~ * &) *)
)
No need to learn it by heart. Simply update the .target
with whatever you want.
See the Pen Last occurrence of an element in the whole document by Temani Afif (@t_afif) on CodePen.
Another example using span
as a selector:
span {
&:nth-last-child(1 of &):not(:has(~ * &) *):not(:has(~ &) *):not(:has(~ * &)):not(:has(&)) {
/* your CSS here */
}
}
See the Pen Last occurrence of an element in the whole document by Temani Afif (@t_afif) on CodePen.