CSS - background color of table row odd/even

后端 未结 9 960

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 backgroun

相关标签:
9条回答
  • 2020-12-10 08:31

    In CSS define the below class

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

    In PHP Code use the below technique

    while($row=mysql_fetch_assoc($q))
    {
        echo "<tr class='color$c'>"; 
        echo "<td>data</td>";
        echo "</tr>\n";
    
        $c=!$c;
    }
    
    0 讨论(0)
  • 2020-12-10 08:32

    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; }
    
    0 讨论(0)
  • 2020-12-10 08:33

    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 ?>">
    ...
    
    0 讨论(0)
  • 2020-12-10 08:36

    just do like this

       $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 讨论(0)
  • 2020-12-10 08:37

    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>
    
    0 讨论(0)
  • 2020-12-10 08:38

    For have a small php inside your html you can use

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

    use alternate between even and odd.

    0 讨论(0)
提交回复
热议问题