Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nth-of-type not working on div

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

like image 773
Geeky Avatar asked Oct 27 '16 18:10

Geeky


People also ask

How do you use the nth-of-type in SCSS?

The :nth-of-type(n) selector matches every element that is the nth child, of the same type (tag name), of its parent. n can be a number, a keyword (odd or even), or a formula (like an + b). Tip: Look at the :nth-child() selector to select the element that is the nth child, regardless of type, of its parent.

What's the difference between the nth-of-type () and Nth child () selector?

As a general rule, if you want to select an interval of a selector regardless of the type of element it is, use nth-child . However, if you want to select a specific type only and apply an interval selection from there, use nth-of-type .

Can you use nth-of-type with a class?

Basic example The selector looks at the type only when creating the list of matches. You can however apply CSS to an element based on :nth-of-type location and a class, as shown in the example above.

What is the nth-of-type pseudo-class when would you apply it?

The :nth-of-type selector allows you select one or more elements based on their source order, according to a formula. It is defined in the CSS Selectors Level 3 spec as a “structural pseudo-class”, meaning it is used to style content based on its relationship with parent and sibling elements.


1 Answers

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

like image 196
ryan Avatar answered Oct 18 '22 00:10

ryan