CSS - odd / even table row background color

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

It makes sense? Thanks!

+4
source share
9 answers

You can use nth-of-type () or nth -child () in CSS3. It is supported by all modern browsers.

For instance...

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; } 
+18
source

Try the following:

CSS

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

in php when printing lines (trs)

 <?php $i = 0; foreach( ... ){ $i = 1-$i; $class = "row$i"; ?> <tr class="<?php echo $class ?>"> ... 
+12
source

In theory, it is as simple as tr:nth-child(even) { background: #999; } tr:nth-child(even) { background: #999; } However, nth-child support is not surprising and will only work with the latest browsers.

An 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> 
+6
source

You can do something like this:

 $counter = 0; while(............){ $counter++; $bgcolor = ($counter % 2 === 0) ? 'red' : 'blue'; } 

Now you can use bgcolor="<?php echo $bgcolor;?>" For your TDs :)

Please note that the above will work in all browsers, including IE6.

+3
source

In CSS, define the class below

 .color0 { #fff; } .color1 { #ccc; } 

In PHP Code use the method below

 while($row=mysql_fetch_assoc($q)) { echo "<tr class='color$c'>"; echo "<td>data</td>"; echo "</tr>\n"; $c=!$c; } 
+3
source

I think the best option is to use an internal foreach iterator:

example:

 <table> <?php foreach ($foo as $key => &$bar) : ?> <tr class="<?php echo ($key + 1) % 2 ? 'odd' : 'even'; ?>"> <td> ... </td> </tr> <?php endforeach; ?> </table> 
+2
source

This is my way, you can try it

 <style type="text/css"> .even{ background-color:#333; } .odd{ background-color:#666; } </style> <?php $i=0; foreach( ... ){ ++$i; ?> <tr class="<?php echo ($i%2) ? 'even' : 'odd' ?>"> <td>..</td> </tr> <?php } ?> 

...

+1
source

For a little php inside html you can use

 <?php echo ($striped)?'even':'odd';$striped=!$striped;?> 

use the alternate between odd and even.

+1
source

just do it

  $codd[0] = 'even'; $codd[1] = 'odd'; $codd_i = 1; foreach($items as $item){ $codd_i = ($codd_i+1)%2; ?> <tr class="<?php echo $codd[$codd_i] ?>"> </tr> <?php } > 
0
source

Source: https://habr.com/ru/post/1337579/


All Articles