0

If I use the following code:

<style>
.a:nth-child(2){
    color: blue
}
</style>

<div class="a">Hello</div>
<div class="b">Goodbye</div>
<div class="a">Hello 2</div>

The text of the second div with the classname of 'a' is not changed to the color blue.

However, if I rearrange the divs

<style>
.a:nth-child(2){
    color: blue
}
</style>

<div class="a">Hello</div>
<div class="a">Hello 2</div>
<div class="b">Goodbye</div>

This works. How would I get the second div by classname as written in the first example using pure CSS?

Also, the :nth-of-type(n) syntax works exactly the same.

Here's a fiddle demonstrating this:

http://jsfiddle.net/mrmayfield/r61pztpb/

Michael Durrant
  • 93,410
  • 97
  • 333
  • 497
Anthony
  • 13,434
  • 14
  • 60
  • 80

1 Answers1

1

You need to use:

.a:nth-of-type(3){
    color: blue
}

Or:

.a:nth-child(3){
    color: blue
}

Since nth-of-type goes by the type of element it is (div in this case) and nth-child goes by the child number within its parent container.

Updated fiddle

kaz
  • 1,190
  • 8
  • 19
  • But if I have content dynamically loading, and I don't know how many divs are in between my first 'a' div and my second 'a' div, how can I structure this in CSS? I would have thought for sure CSS had a function similar to jQuery's .eq() function, but it seems not--I have read the answers of the similar question listed above, but it is still not clear to me whether this functionality is present in CSS3. – Anthony Jun 08 '15 at 00:17
  • 1
    Yeah, you'll have to use javascript at that point. – kaz Jun 08 '15 at 00:19
  • Crazy. Thanks for the help. – Anthony Jun 08 '15 at 00:24
  • 1
    The good news is that there will be something like this in [CSS4](http://css4-selectors.com/selector/css4/structural-pseudo-class/) :-). – kaz Jun 08 '15 at 00:27
  • 1
    @kaz the bad news is that there won't be a CSS4 :P .. CSS3 introduced a modular CSS where each module can have different revisions. Eventually —and hopefully— one day the 3 will drop and it will continue to exist as CSS :D – pgarciacamou Jun 08 '15 at 00:47
  • Well I will eagerly await this feature then! jQuery has a fine API for this kind of work but I'd much prefer to keep my concerns separated. – Anthony Jun 08 '15 at 04:42
  • @Camou: It's neither good news or bad news, just a misinterpretation of the news. There will be a Selectors 4, but nobody knows when browsers will implement the most popular features. – BoltClock Jun 08 '15 at 04:44