Ryan Kennedy
Ryan Kennedy

Reputation: 114

nth odd/even child elements h3

I have a html page setup like so

<div class="row row-venue">
    <div class="col-sm-12">
        <h3>Venue 1</h3>
    </div>
</div>
<div class="row row-venue">
    <div class="col-sm-12">
        <h3>Venue 2</h3>
    </div>
</div>

All I want to do is make every odd h3 a different colour to every even. I have tried with the code below

div.row-venue div.col-venue h3:nth-of-type(odd){
  color:white;
}
div.row-venue div.col-venue h3:nth-of-type(even){
  color:black;
}

and even just tried

h3:nth-of-type(odd){
  color:white;
}

h3:nth-of-type(even){
  color:black;
}

I just cant seem to get my head around it, any help would be appreciated

Upvotes: 2

Views: 542

Answers (2)

Ori Drori
Ori Drori

Reputation: 191976

<h3> is always the first child of <div class="col-sm-12">. Because the counting is zero base - first child = even, so the even rule that you defined applies to all <h3> elements.

To get what you ask, you need to find the nth child between the <div class="row row-venue"> items:

.row-venue:nth-child(odd) h3 {
    color: white;
}
.row-venue:nth-child(even) h3 {
    color: black;
}

If your divs are mixed with other elements, use :nth-of-type instead of :nth-child.

Upvotes: 6

hungerstar
hungerstar

Reputation: 21685

Your CSS is targeting odd/even <h3> tags within a .col-venue element, which I don't see in your markup. Even if .col-venue was in your markup It would only be targeting H3s within it - example here.

You need to control the styling from a higher level in the markup, see below.

<div class="row row-venue">
    <div class="col-sm-12">
        <h3>Venue 1</h3>
    </div>
</div>
<div class="row row-venue">
    <div class="col-sm-12">
        <h3>Venue 2</h3>
    </div>
</div>
.row-venue:nth-of-type(odd) h3 {
    color: red;
}
.row-venue:nth-of-type(even) h3 {
    color: black;
}

http://jsfiddle.net/Lvezzrnq/

With the above CSS selectors you are targeting odd and even .row-venue elements and then drilling down to the h3.

Upvotes: 1

Related Questions