Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nth-child doesn't respond to class selector [duplicate]

Unless it's not supposed to but I can't seem to get nth-child to acknowledge the class selector.

I have say 4 divs inside another div, all of various classes and ids. I need to select the first instance of a div with said class. For example:

#content .foo:nth-child(1) { margin-top: 0; } 

And obviously again with first-child to get the same affect, but it doesn't affect any of the divs.

Now if I want to force it to work with that div I can do this:

#content .foo:nth-child(3) { margin-top: 0; } 

It just so happens that it is the 3rd div in #content, which is pointless because I need to get the 1st instance of anything with that class.

<div id="content">     <div id="action-bar"> </div>   <div id="message"> </div>   <div class="table"> </div>   <div class="clear"> </div> </div> 

Here's a sample of the HTML, I've tried nth-of-type as well like this:

#content .table:nth-of-type(1) { margin: 0 } 

Again it only responds when I say nth-of-type(3).

EDIT:

I've set up a working example of the problem I'm having here: http://jsfiddle.net/aHwS8/

like image 353
stuartc Avatar asked Jul 08 '10 12:07

stuartc


1 Answers

Try the :nth-of-type() pseudo-selector instead:

#content .foo:nth-of-type(1) { margin-top: 0; } 

Note that :nth-of-type() counts the elements with the same name. So .foo:nth-of-type(1) will not select the first element with the class foo but any first element that is the first in the list of elements grouped by the same name. If you have some document like this:

<div>     <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> 

.foo:nth-of-type(1) will select the elements <i class="foo">1</i> and <b class="foo">3</b> as both are the first of its own type.

like image 179
Gumbo Avatar answered Sep 29 '22 19:09

Gumbo