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

2
  • 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 <div> in in the section, so the rule does not apply. Commented Oct 27, 2016 at 18:58
  • @skyline3000..Thanks for clarification Commented Oct 27, 2016 at 19:01

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.