Skip to main content
CSS Tip

Select the first occurrence of an element in the whole document

A CSS selector to select the first occurrence of an element regardless of its position in the document. The equivalent of document.querySelector('.target').

.target { /* Update with what you want to select (class, tag, etc) */
&:nth-child(1 of &):not(:has(&) ~ * *):not(:has(&) ~ *):not(& ~ * *):not(& *) {
/* 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 First occurence of an element in the whole document by Temani Afif (@t_afif) on CodePen.

Another example using span as a selector:

span { 
&:nth-child(1 of &):not(:has(&) ~ * *):not(:has(&) ~ *):not(& ~ * *):not(& *) {
/* your CSS here */
}
}

See the Pen Untitled by Temani Afif (@t_afif) on CodePen.


More CSS Tips