Reputation: 211
Let's say I have a code that looks like this:
while ($info = mysql_fetch_assoc($data_p)) {
$name = stripslashes($info['name']);
$desc = stripslashes($info['description']);
$desc = substr($desc, 0, 150);
$price = stripslashes($info['price']);
Print "<div style=\"width:600px; height:150px; border:1px solid black; overflow:hidden\"><div style=\"height:148px; width:25%; border:1px solid red; float:left\"><center><img src=\"".$picture."\" height=\"120\" width=\"120\" style=\"margin-top:15px\" /></center></div><div style=\"height:150px; width:50%; border:1px solid blue; float:left; text-overflow: ellipsis; padding-top:5px\"><center><font size=\"+1\"><b><a href=\"result.php?product=".urlencode($name)."\">".$name."</b></a></font><br><br>".$desc."...</center></div><div style=\"height:150px; width:24%; border:1px solid green; float:left\"><center><h1>$".$price."</h1><button>Add to Cart</button></center></div></div>";
The main DIV that is first defined in the while loop I would like to alternate two shades of grey. So in the results it would look like light dark light dark etc...I've tried simply repeating the echos again with a different color but that makes duplicates of each result. Is there a way to do this?
Upvotes: 0
Views: 1285
Reputation: 31
You can count amount of DIVs and change color on odd and even.
$num = 0;
while ($info = mysql_fetch_assoc($data_p)) {
$num++;
$color = ($num % 2) ? '#ccc;' : '#aaa';
//***insert your relevant variables
}
Upvotes: 1
Reputation: 2020
If you want to keep your design and logic separated, you can do it with css as well:
div:nth-child(odd) {
background:#c0c0c0;
}
div:nth-child(even) {
background:#a0a0a0;
}
Upvotes: 1
Reputation: 6265
$c = 1;
while ($info = mysql_fetch_assoc($data_p)) {
$name = stripslashes($info['name']);
$desc = stripslashes($info['description']);
$desc = substr($desc, 0, 150);
$price = stripslashes($info['price']);
Print "<div style=\"background:" . ($c ? '#ccc' : '#aaa') . "width:600px; height:150px; border:1px solid black; overflow:hidden\"><div style=\"height:148px; width:25%; border:1px solid red; float:left\"><center><img src=\"".$picture."\" height=\"120\" width=\"120\" style=\"margin-top:15px\" /></center></div><div style=\"height:150px; width:50%; border:1px solid blue; float:left; text-overflow: ellipsis; padding-top:5px\"><center><font size=\"+1\"><b><a href=\"result.php?product=".urlencode($name)."\">".$name."</b></a></font><br><br>".$desc."...</center></div><div style=\"height:150px; width:24%; border:1px solid green; float:left\"><center><h1>$".$price."</h1><button>Add to Cart</button></center></div></div>";
$c = 1 - $c;
Upvotes: 1