CSS Zebra Stripe a Specific Table tr:nth-child(even)

Bill Rosmus picture Bill Rosmus · Sep 15, 2012 · Viewed 7.9k times · Source

I want to zebra stripe only select tables using. I do not want to use jQuery for this.

tbody tr:nth-child(even) td, tbody tr.even td {background:#e5ecf9;}

When I put that in a css file it affects all tables on all pages that call the same stylesheet. What I would like to do is selectively apply it to specific tables.

I have tried this, but it doesn't work.

// in stylesheet
.zebra_stripe{
    tbody tr:nth-child(even) td, tbody tr.even td {background:#e5ecf9;}    
}

// in html
<table class="zebra_even">
<colgroup>
    <col class="width_10em" />
    <col class="width_15em" />
</colgroup>
<tr>
    <td>Odd row nice and clear.</td>
    <td>Some Stuff</td>
</tr>
<tr>
    <td>Even row nice and clear but it should be shaded.</td>
    <td>Some Stuff</td>
</tr>
</table>

And this:

<table>
    <colgroup>
        <col class="width_10em" />
        <col class="width_15em" />
    </colgroup>
    <tbody class="zebra_even">

The stylesheet works as it is properly formatting other elements of the html. Can someone help me with an answer to this problem?

Answer

Spudley picture Spudley · Sep 15, 2012

Your code looks like this:

.zebra_stripe{
    tbody tr:nth-child(even) td, tbody tr.even td {background:#e5ecf9;}    
}

This is wrong (obviously, or you wouldn't need to ask the question), but isn't that far off.

The solution is that you simply need to include .zebra_stripe in the existing CSS selectors. CSS doesn't support multiple tiers of selectors in braces, the way you wrote it. (there are other dialects like Less and Sass that do support this kind of syntax, if you really need it, but in your case the solution doesn't need any clever syntax)

.zebra_stripe tbody tr:nth-child(even) td, .zebra_stripe tbody tr.even td {
    background:#e5ecf9;
}

This assumes you have a table with the class zebra_stripe:

<table class='zebra_stripe'>
    ....
</table>

Tables without the class won't be striped.

By the way, I've left both your selectors in there, but you shouldn't need them both. The nth-child() selector should do the trick on its own, without the tr.even alternative. The tr.even would be needed in browsers that don't support nth-child() (ie old versions of IE), but in that case, if you need to support them, you'd do it with the even class, and wouldn't need to use nth-child().