Skip to content Skip to sidebar Skip to footer

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 colo

Solution 1:

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; }

Solution 2:

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} 

Solution 3:

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.


Solution 4:

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}

Post a Comment for "How Do I Style The Background Color Of Alternating Table Rows?"