0
(0)

In 2022 we have so many CSS selectors, that it’s even hard to keep an evidence of all of them. The next list of pseudo classes are linked to their reference on 3 websites(tympanus , css-tricks and MDN) where these selectors are explained by the author(kudos for tympanus and Chris Coyier and MDN team for the great reference):

So where is the :first-of-class ? Nowhere ! The :first-of-type got closer to the idea, but that only targets the first of the same tag name(doesn’t help). There is that futuristic example, where an :nth-child can get 2 arguments:

:nth-child( <nth> [ of <complex-selector-list> ]? )

Ex: p:nth-child(1 of .box)

You guessed it folks, the support is very bad, so it’s not even worth mentioning.

Well, for now what we can do is, create a workaround that kind of does what the :nth-of-class would have done.

Make the first element that has the class name .box to have bolded text !

.box {
   font-weight:bold;
}
.box ~ .box {
   font-weight: normal;
}

We add bolded style on all .box class but we revert it to normal style for every .box that comes after a .box. By exclusion only the first element with class .box does not have a .box before it.

Make the first and second .box element have bolded text !

.box, .box ~ .box {
   font-weight:bold;
}
.box ~ .box ~ .box {
   font-weight: normal;
}

This would be equivalent with :is(:nth-of-class(1), :nth-of-class(2)) or :nth-of-class(-n + 2). What I did here is, I added bold to all .box classes and all .box classes that come after a .box class. But I reverted to normal for those .box classes that come after a .box class that comes after a .box class (not necessarily immediately after).

Let’s top up the game ! Let’s make the 1st, 2nd and 4th .box bolded but not the 3rd or the rest !

.box, .box ~ .box ~ .box ~ .box {
   font-weight:bold;
}
.box ~ .box ~ .box {
   font-weight: normal;
}

In this case what happened?

  • added on every .box(1) element – a bold
  • I ommited the .box ~ .box to target the second element because that was covered by adding on every .box element a bold
  • added on every .box(3) that comes after a .box(2) that comes after a .box(1) – a normal style (the 3rd and all after the 3rd will be normal style)
  • added on every .box(4) that comes after a .box(3) that comes after a .box(2) that comes after a .box(1) – a bold (the 4th and the rest will be bolded)
  • added on every .box(5) that comes after a .box(4) that comes after a .box(3) that comes after a .box(2) that comes after a .box(1) a normal (this overrides the previous rule – so the 5th and the rest will be normal style again)

Target the last-of-class(.box) if you can !

Well I couldn’t think of anything, so this could be a challenge for you guys ! Happy coding !

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Categorized in: