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.
More CSS Tips
- Folded rectangle shapes using CSS mask Create a folded rectangle shape with minimal code and a subtle 3D effect.
- Indent each line of your text A new value of text-indent that allows you to indent each line of text.
- How to correctly define a one-color gradient The most optimized way to create a one-color gradient.
- Avatar hover effect with a rhombus shape Add a fancy hover effect to your image with a simple code.