0

I've got a div with a number of image + text divs, the images and text divs appear in a random order, it could be image-image-text-image or text-image-text-image etc... each text item has a class associated with it, so how do I target the nth element of that class?

I can't target the parent as the first item may be an image or text and I only want to target each text item individually. This is the class applied to the variable number of divs in a variable order:

.article_content_divs {
    width:720px;
    float:left;
    margin-left:5px;
    margin-top:5px;
    text-align:justify;
}
1
  • Would be better if you add the code :) Jul 2, 2014 at 23:29

1 Answer 1

0

You can use :nth-of-type(n). However, that requires you to use different types rather than different classes.

So instead of have <div class="image"> and <div class="text">, you would need to have <div class="image"> and <p class="text"> for instance (or simply <div> and <p>, that's all that matters).

Then you can use selectorforparent p:nth-of-type(n).

Note that nth-of-type is relatively recent, so you'll have to check backwards compatibility.

3
  • It doesn't seem to be working on safari mac
    – Crizly
    Jul 2, 2014 at 23:32
  • Works here. Not that your text and image elements must be different types (e.g. p vs img, or p vs div, or anything else you fancy), and you must include the type in the selector: p:nth-of-type(3)
    – jcaron
    Jul 2, 2014 at 23:36
  • he does not target types here, he wants to target classes, that's why it does not work.
    – King King
    Jul 2, 2014 at 23:43

Not the answer you're looking for? Browse other questions tagged or ask your own question.