Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS - background color of table row odd/even

Tags:

css

php

I have a table that is dynamically generated by PHP. I am hoping that I can use CSS to apply a background color based on where the table row is odd/even, i.e. the background color rotates every other row.

Does that make sense? Thanks!

like image 952
user547794 Avatar asked Jan 29 '11 09:01

user547794


3 Answers

You can use the nth-of-type() or nth-child() selector in CSS3. Supported by all modern Browsers.

For example...

tr:nth-child(odd) { background-color: #ccc; }

/* Do this… */
tr:nth-of-type(odd) { background-color: #ccc; }

/* …or this */
tr:nth-of-type(even) { background-color: #ccc; }
like image 98
gearsdigital Avatar answered Oct 22 '22 05:10

gearsdigital


Try this :

css:

.row0{
 background:white;
}
.row1{
 background:black;
}

in php while printing rows (trs)

<?php

$i = 0;
foreach( ... ){

$i = 1-$i;
$class = "row$i";
?>
<tr class="<?php echo $class ?>">
...
like image 12
Arshdeep Avatar answered Oct 22 '22 06:10

Arshdeep


In theory it's as easy as tr:nth-child(even) { background: #999; } However, support for nth-child isn't amazing and will only work on the newest browsers

Example:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html lang="en">
  <head>
    <title>Test</title>
    <style type="text/css">
      thead, tr:nth-child(even) { background: #aaa; }
    </style>
  </head>
  <body>
    <table>
      <thead>
        <tr><th>Header</th><th>Header</th></tr>
      </thead>
      <tr><td>Data</td><td>Data</td></tr>
      <tr><td>Data</td><td>Data</td></tr>
      <tr><td>Data</td><td>Data</td></tr>
    </table>
  </body>
</html>
like image 6
Gareth Avatar answered Oct 22 '22 05:10

Gareth