开发者

change css for every 4th row

开发者 https://www.devze.com 2023-03-23 21:32 出处:网络
I want to display every 4th row grabbed from the database with different CSS: <div cl开发者_开发技巧ass=\"last\"></div>

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

<div cl开发者_开发技巧ass="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>

Use % to get division remainder, if it equals zero then it is exatly forth div and we need to print it with class, otherwise print nothing.


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.


<?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>";
?>


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 i.e 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

0

精彩评论

暂无评论...
验证码 换一张
取 消