user3007294
user3007294

Reputation: 951

nth Child in CSS

I have used nth child before but for some reason can not target the correct div:

<div class='main'>...</div>
  <div class='color'>...</div>
  <div class='number'>...</div>
    <div class='target_div'>...</div>
      <div class='target_me_one'>...</div>
      <div class='target_me_two'>...</div>
<div class='main'>...</div>
<div class='main'>...</div>
<div class='main'>...</div>
<div class='main'>...</div>
<div class='main'>...</div>
<div class='main'>...</div>

I was hoping for the first occurrence of main, the second child of main (number), the first child of number (target_div) and then both of the children of target_div.

The whole objective of this is to alter target_me_one / target_me_two all from the first occurrence of main. I can not target these two individually through selectors (due to the plug in I'm using).

Is this possible or am I way off???

Upvotes: 0

Views: 83

Answers (3)

xian
xian

Reputation: 4693

This will do what you are expecting, without relying on classes for specific selectors. Check out the JSFiddle

      .main:first-of-type > *:nth-child(2) > *:nth-child(1) * {
        color: red;
      }

Upvotes: 1

OJFord
OJFord

Reputation: 11130

You do not have any child elements to select.

What you are probably thinking of is the :nth-of-type selector.

e.g.:

.main{
    /* All */
}

.main:nth-of-type(1){
    /* First */
}

.main:nth-of-type(2){
    /* Second */
}

See the documentation.

As usual, note that this does not work in IE <9.

Upvotes: 1

masum7
masum7

Reputation: 832

Use "first-of-type" instead of n-th child.

here is the jsfiddle: http://jsfiddle.net/m395kdxy/

    .main:first-of-type .target_me_one {
        background: #ff0000;
    }

    .main:first-of-type .target_me_two {
        background: #ff0000;
    }

Please let me know if it works

Upvotes: 1

Related Questions