0

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

shriek
  • 5,605
  • 8
  • 46
  • 75

1 Answers1

0

Because the type is tag type (li). And there is only one first li in your ul.

Think of the selector as condition requiring that: Target has to be first of its kind in parent and at the same time it has to have data-year value equal to XXXX.

Just do it with JavaScript or add CSS classes. :)

Klímačka
  • 261
  • 1
  • 3
  • 16
  • "Target has to be first of its kind in parent and at the same time it has to have data-year value equal to XXXX" - is it first element of it's kind or just first type of it's kind? I'm starting to suspect it's the former. Also, I'm trying to avoid using JS as much as I can and only setting it as my last resort. *Edit- Okay, from the related links posted it looks like it's a common misconceptions* – shriek Apr 06 '19 at 20:53