I found many articles online about coloring alternate table rows. what about if I want use different colors for individual rows, how can I do that?
<table class="table1">
<tr>
<th>Name</th>
<th>Surname</th>
<th>Email</th>
</tr>
@{ foreach (var p in Model.People)
{ <tr>
<td>@p.Name</td>
<td>@p.Surname</td>
<td>@p.Number</d>
</tr>
}
}
</table>
How to color specific row in a CSS Table. You can use the tr:nth-child(rownumber) to color a particular row in a table using CSS. Above code select the 3 row from top (including table head row) and color background as green and foreground as white.
HTML | <tr> bgcolor Attribute The HTML <tr> bgcolor Attribute is used to specify the background color of a table row. It is not supported by HTML 5. Attribute Values: color_name: It sets the background color by using the color name.
The background color of the table is given by the bgcolor="color" attribute. When applied to the <table> tag, the color fills the background. Cell background colors are set by applying the bgcolor attribute to a <tr> tag (to color the row) or to a <td> tag (to color the cell).
In HTML, table background color is defined using Cascading Style Sheets (CSS). Specifically, you use the background-color property to define background color. You can apply this property against the whole table, a row, or a single cell.
You can have in your css
.table1 tr:nth-child(1) { background:blue; }
.table1 tr:nth-child(2) { background:red; }
.table1 tr:nth-child(3) { background:orange; }
...
See demo http://jsfiddle.net/wnCgL/
Edit
with jQuery, using a random color function
$(function() {
$('.table1').find('tr').each(
function() {
$(this).css('background', get_random_color());
});
});
http://jsfiddle.net/wnCgL/1/
For example like this. Define some enumm or you can later generate colors by random:
public enum Colors
{
Blue = 1,
Red = 2,
Yellow = 3,
Pink = 4,
Green = 5,
}
then in markup file get random color from enum
@{ foreach (var p in Model.People)
{ <tr style="background-color:@(Colors[new Random().Next(0,Colors.Length)])">
<td>@p.Name</td>
<td>@p.Surname</td>
<td>@p.Number</d>
</tr>
}
}
Update: Or if you want to make it more readable for users use odd and even css styles.
Check this fiddle - http://jsfiddle.net/r74j6/6/
Or this post - Apply different background color using jquery
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With