Style alternating rows in a table
Two ways to style alternating rows in a table.
First, we can us CSS3 to style the alternating rows of any table using a simple pseudo class tag on a table class. Something like this:
1 2 | tr:nth-child(even) {background: #CCC} tr:nth-child(odd) {background: #FFF} |
The issue is that not all browsers support this type of css. It is getting better and most modern browsers will work with this and is probably the best way to code this going forward. I myself have since taken this route on instead of the following alternative.
The alternative is to set a class on each table row. This is easy in Web Forms with a GridView or ListView. They have an AlternateRowStyle tag or AlternateStyle template that takes care of things.
Obviously this control does not exist in the MVC world. I had also seen things like setting an “index” variable and then increment this each time in the loop. I knew I had to get the index of the iteration in a previous project so I figured why create another variable when I don’t have to. I am all about minimal code to do maximum things. Using what is already created in memory to accomplish more than one task. I also really like Lamba syntax. I think it is elegant and easier to follow, once you know how to read it. Here is the code sample to style alternating rows in a table
1 2 3 4 5 6 7 | @foreach(var item in Model.Select((value, i) => new {Data = value, Index = i})){ <tr class=@(item.Index % 2 == 0? "even" : "odd") > ... } |
You simply create two classes in CSS one called “even” and one called “odd” with your alternating color scheme. When the page is rendered even rows will get the “even” class set and odd rows will get the “odd” class. It is that simple to style alternating rows in a table with Razor. At the time of this writing this is one way. As more and more browsers adapt CSS3 standards these types of tricks will become less and less needed.