如何在PHP中每隔一个div交替背景颜色

时间:2012-09-13 00:53:36

标签: php

我目前正在创建一个带有博客平台的网站,我希望主页上的所有其他帖子容器都有替代颜色。像浅蓝色,然后是深蓝色,浅蓝色,深蓝色,浅蓝色等。我正在使用while循环从mysql数据库中获取5个帖子。这是我的代码。

<?php
$sql = mysql_query("SELECT * FROM posts ORDER BY id DESC LIMIT 6");
$array = mysql_fetch_array($sql);
while ($array = mysql_fetch_array($sql)) {

//The php below this is the problem

$counter = 0;
$counter++;

$postcolour =  WHAT DO I PUT HERE ? 'lightblue' : 'darkblue';


?>


<div class="postcontainer" style="background-color: <?php echo $postcolour; ?>;">
</div> <?php } ?>

2 个答案:

答案 0 :(得分:4)

只需使用modulus两个:

$postcolour = $counter % 2 ? 'lightblue' : 'darkblue';

答案 1 :(得分:4)

我只是使用CSS:

.postcontainer {
    background-color: lightblue;
}

.postcontainer:nth-of-type(even) {
    background-color: darkblue;
}

Here's a demo!