6

I'm confused with nth-of-type selector.

I have tried this snippet

.red:nth-of-type(1){
  color:red;
}
<div class="home">
  <span>blah</span>
  <p class="red">first</p>
  <p class="red">second</p>
  <p class="red">third</p>
  <div class="red">fourth</div>
</div>

It gets both p and div with class red and changes its color

Now i'm stuck with this example

section .foo:nth-of-type(1){
  background:red;
}

.parent .foo:nth-of-type(1){
  background:red;
  }
<section>

  <p class="foo">Little</p>
  <p>Piggy</p>
  <div>...</div>
  <div class="foo">border...</div>
</section>

<div class="parent">
  <i class="foo">1</i>
  <i>x</i>
  <i class="foo">2</i>
  <b class="foo">3</b><b>x</b><b class="foo">4</b>
</div>

I was expecting both p and div in the section with class foo to get red background but it does not work, it works well when div is replaced with span

but,other styles to parent div in the code works correctly and styles i and b

I know this is a duplicate of CSS selector for first element with class

Community
  • 1
  • 1
Geeky
  • 7,420
  • 2
  • 24
  • 50
  • 1
    nth-of-type works on matching elements, not classes. So you expect `border...` to have a red background, but in fact that is the second `
    ` in in the section, so the rule does not apply.
    – skyline3000 Oct 27 '16 at 18:58
  • @skyline3000..Thanks for clarification – Geeky Oct 27 '16 at 19:01

1 Answers1

6

It is because the div with class 'foo' is not the first child of that type, it is the second. The selector will only match elements that are the first of there type and have the class 'foo'.

It doesn't match the first of that type AND class like you are expecting

ryan
  • 1,451
  • 11
  • 27