Sachindra
Sachindra

Reputation: 6969

How do I style the background color of alternating table rows?

I was was just wondering how to get this kind of design done when things are fetched dynamically? I mean there has to be only one class which can be used to get the background colour depending upon whether block is odd or even. I hope my requirements are clear: background color varying with the odd or even number for the rows.

alt text

Upvotes: 4

Views: 11251

Answers (4)

Jeepstone
Jeepstone

Reputation: 2601

As you've not specified a language for what's returning the code I'll give you a pure CSS answer.

tr:nth-child(2n+1) {YOURSTYLEINHERE}
or
tr:nth-child(odd) {YOURSTYLEINHERE} 

Upvotes: 3

Steven
Steven

Reputation: 18004

You're looking for alternating rows. This is accomplishable by adding a different class to every other row.

Tutorials are plenty on how to do this.

CSS3 also provides a new way to do this without adding classes:

tr:nth-child(odd)   { background-color:#eee; }
tr:nth-child(even)    { background-color:#fff; }

Upvotes: 6

dstarh
dstarh

Reputation: 5076

What you want is modulus division

if(rowNum % 2 == 0) {class="even"} else {class="odd"}

OR if you are using CSS3 you can do it like this

tr:nth-child(even) {background: #CCC}
tr:nth-child(odd) {background: #FFF}

Upvotes: 0

Chris B. Behrens
Chris B. Behrens

Reputation: 6297

Add a second css class for the alternating row. Assuming that the default bg color here is dark gray, the second class would look like this:

.altRow { background-color:white !important; }

If you don't want to have to code the logic server-side for applying the second class, you can use JQuery's Odd selector. But that's about as close are you're going to get to zebra-striping without just manually applying a second class.

Upvotes: 0

Related Questions