Skip to main content
CSS Tip

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:

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.


More CSS Tips