Archive | HTML/JS/CSS RSS feed for this section

nth Child in CSS

30 Apr

An easy way to alternate colors in a table list in CSS
is by the following rule :
tr:nth-child(even) {background: #CCC}
tr:nth-child(odd) {background: #FFF}

This can save a lot of code, as the alternative was to do it in php :

echo "<table>";
foreach($arr as $k=>$v) {
echo "<tr";
if ($count++ %2) {
    echo " class=\"odd\"";
} else {
    echo " class=\"even\"";
}
echo "><td><strong>{$k}</strong></td><td>{$v}</td></tr>\n";
}
echo "</table>";

is now reduced to :

echo "<table>";
foreach ($k=>$v) echo "<tr><td><strong>{$k}</strong></td><td>{$v}</td></tr>\n";
echo "</table>";

Hope that helps someone out.