Nth-of-type() question

Why the selector nth-of-type(3) select the second “ye” and not the third?

<div class="yo">
  <div class="ya"></div>
  <div class="ye"></div>
  <div class="ye"></div>
  <div class="ye"></div>
.yo {
  display: flex;
  gap: 1em;

.ye {
  height: 3em;
  background-color: red;
  width: 5em;

.ye:nth-of-type(3) {
  background-color: green;


I’ve battled with your code for a while here and I’ve finally figured out why, lol! It’s because the nth-of-type selector selects tags rather than classes. It only works for tags. Mozilla says:

The :nth-of-type() CSS pseudo-class matches elements based on their position among siblings of the same type (tag name).

See tag name up there? That’s why. My suggestion is to change .ye to div and n to 4. Or maybe someone more experienced can offer a better explanation and solution.
Nicolas, 17

when you said “tag name” you mean to element name?

Yes, as in div.

Here, read this - I think it’ll help:
:nth-of-type() - CSS: Cascading Style Sheets | MDN

this have the same result

<div class="yo">
  <label class="ya"></label>
  <div class="ye"></div>
  <div class="ye"></div>
  <div class="ye"></div>

Could you give me an updated codepen? I can’t quite see what you mean.

Wait, you haven’t changed .ye in the nth-of-child yet.

matches elements based on their position among siblings of the same type (tag name) .ye have the tag of div

yeah you are right, I forget change it back to nth-of-type

Here’s a fiddle that works, I think.

Yeah, I was going to explain that. What I did is put nth-of-type there and put in three. Does that work for you?

now work as expected, there is a selector that select the silbings among class?

~ is a css sibling selector. You can look it up if you’re interested. I don’t know if that’s what you need or not.
I hope I solved your problem though…
Here: CSS Combinators
Scroll down a bit to see it.

my problem was don’t read the documentation so you solved it thanks.
I guess ~ can work as nth-of-type but will be a little tricky
.ye~.ye~.ye to select the third .ye

Yeah, that is a bit sticky. Anyway, thx and have a good coding day!

1 Like