tags:

views:

53

answers:

2

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/

A: 

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.

Gumbo
Thanks! I tried got the same response, it responded to: #content .foo:nth-of-type(3) { margin-top: 0; }
stuartc
It's kind of similar, it's like it's ignoring the .foo class and just selecting the divs
stuartc
@stuartc: It does not ignore the class. `.foo:nth-of-type(3)` does only apply to those elements that have the class “foo” *and* are the third of its type (there are only 2 other siblings with the same element name before this element).
Gumbo
A: 

I think you're using the wrong selector, try:

#content .foo:first-of-type { margin-top: 0; }
Jake
Thanks! I tried got the same response, it responded to: #content .foo:nth-of-type(3) { margin-top: 0; }
stuartc
Hmm, I see - so what you want is the first `div` with class `.foo` regardless of which child it is. But what this selector does is the first `div` if it also has class `.foo`?From a quick google and look at the CSS3 Pseudo-Selectors I'm not sure this is possible. Sorry I couldn't be more help!
Jake
Thanks for your help, despite not fixing my issue, I've learnt a lot about pseudo-selectors! :) thanks again!
stuartc