CSS - 表格行/奇数的背景颜色

use*_*794 4 css php

我有一个由PHP动态生成的表.我希望我可以使用CSS根据表格行奇/偶的位置应用背景颜色,即背景颜色每隔一行旋转一次.

那有意义吗?谢谢!

gea*_*tal 18

您可以在CSS3中使用nth-of-type()nth-child()选择器.所有现代浏览器都支持.

例如...

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; }
Run Code Online (Sandbox Code Playgroud)


Ars*_*eep 12

试试这个 :

CSS:

.row0{
 background:white;
}
.row1{
 background:black;
}
Run Code Online (Sandbox Code Playgroud)

在php中打印行(trs)

<?php

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

$i = 1-$i;
$class = "row$i";
?>
<tr class="<?php echo $class ?>">
...
Run Code Online (Sandbox Code Playgroud)

  • @diEcho - `$ i = 1- $ i;`将在0和1之间切换$ i (9认同)

Gar*_*eth 6

从理论上说它很容易tr:nth-child(even) { background: #999; }然而,对nth-child的支持并不令人惊讶,只适用于最新的浏览器

示例:

<!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>
Run Code Online (Sandbox Code Playgroud)


Sar*_*raz 3

你可以这样做:

$counter = 0;
while(............){
  $counter++;

  $bgcolor = ($counter % 2 === 0) ? 'red' : 'blue';

}
Run Code Online (Sandbox Code Playgroud)

现在您可以用于bgcolor="<?php echo $bgcolor;?>"您的TDs:)

请注意,上述内容适用于所有浏览器,包括 IE6。