I want to write a CSS selector which matches the first occurrence of an element with class “icon”. The elements haven’t got a common parent (as seen below), so the :first-child or :first-of-type pseudos didn’t work for me.
The HTML markup isn’t very good, but its specification, so it’s not possible to change it.
Is there any CSS only solution, to match the first occurence of an element?
<div>
<div class="icon"></div> <!-- only this should be matched -->
<p class="categoryTitle">Category 1</p>
<ul>..</ul>
</div>
<div>
<div class="icon"></div>
<p class="categoryTitle">Category 1</p>
<ul>..</ul>
</div>
<div>
<div class="icon"></div>
<p class="categoryTitle">Category 1</p>
<ul>..</ul>
</div>
OR
<div>
<!-- nothing here -->
</div>
<div>
<div class="icon"></div> <!-- only this should be matched -->
<p class="categoryTitle">Category 1</p>
<ul>..</ul>
</div>
<div>
<div class="icon"></div>
<p class="categoryTitle">Category 1</p>
<ul>..</ul>
</div>
OR
<div>
<!-- nothing here -->
</div>
<div>
<!-- nothing here too -->
</div>
<div>
<div class="icon"></div> <!-- only this should be matched -->
<p class="categoryTitle">Category 1</p>
<ul>..</ul>
</div>
No, there isn’t. You’d have to find out which of the parent
divelements have.iconchildren in the first place, which you can’t do with CSS selectors. The jQuery selector.icon:firstdoes exactly what you want, but:firstis not part of CSS.