You can't achieve this with only CSS. However, JavaScript's document.querySelector
can be used to obtain the first element on the page matching a selector.
const first = document.querySelector('.something');
first.style.backgroundColor = "dodgerblue";
<div>
<span class="something">...</span>
<span class="something">...</span>
<span class="something">...</span>
</div>
<article>
<span class="something">...</span>
</article>
In order to affect pseudo elements, you can add a class to the element found with document.querySelector
and add another style declaration in your CSS.
const first = document.querySelector('.something');
first.classList.add("first");
.something.first:after {
content: "I'm the first one!";
color: dodgerblue;
}
<div>
<span class="something">...</span>
<span class="something">...</span>
<span class="something">...</span>
</div>
<article>
<span class="something">...</span>
</article>
`
– Shamoon Jul 14 '20 at 18:45