I thought this would be pretty straight forward but apparently I haven't been able to wrap my head around it.
The HTML in question:
<ul>
<li data-year="2020"> <span>Year 2020 List 1<span> </li>
<li data-year="2020"> <span>Year 2020 List 2</span> </li>
<li data-year="2021"> <span>Year 2021 List 1 </span> </li>
<li data-year="2021"> <span>Year 2021 List 2</span> </li>
<li data-year="2021"> <span>Year 2021 List 3</span> </li>
</ul>
The CSS for the HTML:
[data-year="2020"]:first-of-type {
color: red;
}
[data-year="2021"]:first-of-type {
color: green;
}
What I'm trying to achieve is to apply color to first span
of element that has date-year=2020
and date-year=2021
attributes. i.e. "Year 2020 List 1" and "Year 2021 List 1".
From my brief look at MDN first-of-type
is only applied to any first child type of the targeted selector and that's what I thought was supposed to happen in the above code but I'm only seeing "2020 List 1" with the applied color but not "2021 List 1".
I'm starting to wonder if it's even possible to do what I'm trying to do in CSS at all without making significant modification to my HTML structure.
https://jsbin.com/dijerihako/edit?html,css,output
Edit: As from the posted related link it looks like there's no way to do what I'm trying to do yet in CSS. The aforementioned link does post a workaround though
Unfortunately, there is no similar :first-of-class pseudo-class for matching the first child element of a given class. One workaround that Lea Verou and I came up with for this (albeit totally independently) is to first apply your desired styles to all your elements with that class