Reputation: 63
I'm using Dreamweaver and I want to color the rows of a dynamic table alternately. I can't seem to find any answers that work for me or that I understand. Could you give a sample CSS on how to do it? Explanations would help because I'm not confident in coding yet.
I'm using the Chrome browser.
Upvotes: 0
Views: 5989
Reputation: 3
If I generate a table using PHP, I use two (or more) CSS classes that are applied to the tags of the table I want formatted.
#my_table tr.r0 td {
background-color: #123;
}
#my_table tr.r1 td {
background-color: #456;
}
In other words, the two CSS statements above mean: set background color of any <td>
in a <tr>
with class r0/r1 to #123/#456, only in table with id #my_table.
When you generate the rows of your table, you can set a counter that always increase by 1 every row (useful if your row generation have weird conditions that can prevent some rows to appear or generate a variable number of rows) and I use the modulo 2 (% 2
) of the counter to decide if the row is even or odd. Even rows yield 0 and odd rows yield 1.
echo '<tr class="r' . ($counter % 2) . '">';
This lets you have any number of types of colors for rows.
Or, if you only have 2 row colors, you can use a variable that is set to 0 initially, and toggle between 0 and 1 every time you generate a row, like this:
$counter = !$counter;
Or use C-style if-then-else construct (less readability):
$counter = $counter ? 0 : 1;
Upvotes: 0
Reputation: 41
I updated this to provide a better example by showing an actual HTML page.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("tr:even").css("background-color", "#eeeeee");
$("tr:odd").css("background-color", "#ffffff");
})
</script>
</head>
<body>
<table>
<tr>
<td>Col 1</td>
<td>Col 2</td>
</tr>
<tr>
<td>1</td>
<td>Cat</td>
</tr>
<tr>
<td>2</td>
<td>Dog</td>
</tr>
<tr>
<td>3</td>
<td>Mouse</td>
</tr>
</table>
</body>
</html>
Upvotes: -3
Reputation: 86
Try adding this to your css and it should work with all the modern browsers:
tr:nth-child(odd) {
background-color:#eee;
}
tr:nth-child(even) {
background-color:#fff;
}
Upvotes: 6
Reputation: 14348
Us enth-child
http://jsfiddle.net/37bv1s14/
<table>
<tr>
<td>aa</td>
<td>sadfdf</td>
</tr>
<tr>
<td>aa</td>
<td>sadfdf</td>
</tr>
<tr>
<td>aa</td>
<td>sadfdf</td>
</tr>
<tr>
<td>aa</td>
<td>sadfdf</td>
</tr>
CSS
table{
border:1px solid;
}
tr:nth-child(even){
background-color:green;
}
tr:nth-child(odd){
background-color:yellow;
}
Upvotes: 1