简体   繁体   中英

Alternative Table Row Colors

Checked already answered questions but unsuccessful.

I have table populated from database.

How to make alternative color for each group ? such as this

在此处输入图片说明

This is the code

<?php
while ( $rq  = sqlsrv_fetch_array( $result_N, SQLSRV_FETCH_ASSOC)) {
?>

<div class="center2">
  <div class="datagrid">
    <table>
        <tr><td> <?php echo $rq[category_id]; ?></td></tr>
    </table>
    </div>
</div>
<?php } ?>

Thank you

PS

It's a no problem to create row alternative such as this

在此处输入图片说明

But I looking for GROUP by ID

Use css nth child.

For even/odd

Tr:nth-child(even){
 Background-color: #446;
}

For Class

Tr.bg{
 Background-color: #446;
}

For more information

https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-child

With PHP alternating based on variable. This code will change class if the first letter changes.

<?php

 $first_letter  '';
 //Change class to true to invert background color
 $class = false;


//Warning isn't Category id supposed to be a string is so add quotes

 while ( $rq = sqlsrv_fetch_array( $result_N, SQLSRV_FETCH_ASSOC)) { 
//Using shorthand echo <?=
//

     // CSS Class Name
    $val = (string) trim( strtolower( $rq[category_id] ) ); //Make sure its of string type

    //This will set the class to either true or false
    //If class is true, the column will have a classname of bg
    if( !empty( trim($rq[category_id]) ) && strlen( $val ) > 0 && $first_letter !== $val[0];   ){
        $class = !$class; //Invert class
        $first_letter = $val[0];
    }

   ?> <div class="center2"> 
    <div class="datagrid"> 
       <table> 
          <tr class='<?= $class ? 'bg' : null  ?>' ><td> <?php echo $rq[category_id]; ?></td></tr> 
       </table> 
    </div> 
   </div><?php

} 

If you're iterating through the rows with an index, check the value of index % 2 which say's "what's the remainder, if any, of index divided by 2 ?"

If it equals 0 then set it's class to something like even-row otherwise set it's class to something like odd-row .

You can use getElementsByClassName() to get all elements and loop through the returned array, setting the background color on every second element. See below:

 <!DOCTYPE HTML> <html> <body> <p class="row">A Row</p> <p class="row">A Row</p> <p class="row">A Row</p> <p class="row">A Row</p> <p class="row">A Row</p> <p class="row">A Row</p> <p class="row">A Row</p> </body> <script> const rows = document.getElementsByClassName('row'); for (i=0;i<rows.length;i+=2) rows[i].style.backgroundColor = "blue"; </script> </html>

If you want to use CSS, use nth-child.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM