Add Alternate Background Style To Odd Rows Of Html Table
I am creating an email log to report on activities of my application. The table is working finr but when hundreds of records are output it is difficult to read. Here is my existing
Solution 1:
tbodytr:nth-child(even) {
background-color: #bada55;
}
tbodytr:nth-child(odd) {
background-color: lightblue;
}
Solution 2:
Cross Browser solutions
Option 1: jQuery
If you're not intending to support IE8 or less then the nth-child
selector will not work for you. However, using jQuery you can simply add the following as jQuery does support nth-child
. Or alternatively, in jQuery you can use :even
and :odd
. You'd need to figure out when to call this though.
$("tbody > tr:even" ).css("background-color", "blue");
$("tbody > tr:odd" ).css("background-color", "red");
Option 2: no jQuery
Or from your code have:
var count =0;
foreach (task_creditcases item in creditCases)
{
if (count++%2==0)
sb.Append("<tr class=\"even\">");
else
sb.Append("<tr class=\"odd\">");
// Rest of sb.code
}
Then in your CSS
file add:
tbody > tr.odd { background-color: red; }
tbody > tr.even { background-color: blue; }
I'd recommend the second option since you wouldn't have to touch jQuery which applies the styles inline. Performance is better if the styles are in the CSS vs inline.
Solution 3:
tr:nth-child(odd) {background: #FFF}
or
tr:nth-child(even) {background: #FFF}
Add one of those to your css, depending on even or oneven rows.
Solution 4:
thanks everyone,
here is what I did before I saw jumpingcode's answer:
foreach (task_cases item in cases)
{
//sb.Append("<tr>");var idx = 0;
bool even = idx % 2 == 0;
if (even)
{
sb.Append("<tr background-color:#eee;>");
}
else
{
sb.Append("<tr background-color:#fff;>");
}
Post a Comment for "Add Alternate Background Style To Odd Rows Of Html Table"