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:
- It's the first element among its siblings having the same class (
&:nth-child(1 of &)
) - It's not the child of an element with the same class (
:not(& *)
) - It's not the child of an element that is preceded by an element with the same class (
:not(& ~ * *)
) - It's not preceded by an element having an element with the same class (
:not(:has(&) ~ *)
) - It's not the child of an element that is preceded by an element having an element with the same class (
:not(:has(&) ~ * *)
)
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.