简体   繁体   中英

change css for every 4th row

I want to display every 4th row grabbed from the database with different CSS:

<div class="last"></div>

but the rest of them should be displayed normaly:

<div></div>

I am using simple query to grab data from database:

SELECT LEN(column_name) FROM table_name

I saw this type of thing but I don't remember how to do it properly. Any ideas?

using css like

tr:nth-child(4n) {  
   background-color:yellow;
} 
<div<?php echo $i % 4 == 0 ? ' class="last"' : '' ?>>...</div>

使用 % 得到除法余数,如果它等于零,那么它就是第四个 div,我们需要用 class 打印它,否则什么都不打印。

<?php 
    $query = "SELECT LEN(column_name) FROM table_name";
    $result = mysql_query($query);
    $i = 1;
    echo  "<table>";
    while ($row = mysql_fetch_assoc($result)) {
        echo  "<tr><td>";
        echo  "<p";
        if ($i % 4 == 0) print " class='stripe'";
       echo  ">" . $row['item'] . "</p></td></tr>";
        $i++;
     }
    echo  "</table>";
?>

This is not the sort of thing you should do in SQL. Have a variable in PHP act as a counter starting from 0, and use the alternate class when the modulus of 4 of the counter is 3.

the qustion is absurd I dnt ustand why you are trying to set your css style in the db.. its illogical to do so and you will unnecessarily increase the complexity of your query.

Anyways my suggestion would be to do the same in your web tier ie once you retrieve the records from the db and rendering the page. just write sm logic that will add the css class..

Something like this:

<?php 
    $query = "SELECT LEN(column_name) FROM table_name";
    $result = mysql_query($query);
    $i = 1;
    print "<table>";
    while ($row = mysql_fetch_assoc($result)) {
        print "<tr><td>";
        print "<p";
        if ($i % 4 == 0) print " class='stripe'";
        print ">" . $row['item'] . "</p></td></tr>";
        $i++;
     }
     print "</table>";
?>

Don't do it with SQL queries, do it with PHP:

  $result = mysql_query("SELECT * FROM table_name");
  $i = 1;    
  while($row = mysql_fetch_array($result))
  {
     $class = ($i % 4 == 0) ? ' last' : '';        
     echo '<div class="'.$class.'"></div>';
     $i++;
  }

This is how Bootstrap does it

.table-striped tbody tr:nth-child(odd) {  
    background-color: rgba(0, 0, 0, 0.05);
} 

So you can create your own class and replace odd with 4n

.table-striped-4th tbody tr:nth-child(4n) {  
    background-color: rgba(0, 0, 0, 0.05);
} 

https://developer.mozilla.org/en-US/docs/Web/CSS/: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