Geeky Geeky - 1 year ago 102
CSS Question

nth-of-type not working on div

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

I have tried this snippet


<div class="home">
<p class="red">first</p>
<p class="red">second</p>
<p class="red">third</p>
<div class="red">fourth</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){

.parent .foo:nth-of-type(1){


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

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

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

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download