noscript-img
HomeAboutLinux NewsLinksPrivacy
My Computer Tips Home

Alternating div background colours using CSS

ID: 259

Category: CSS

Added: 9th of April 2021

Views: 7,217

If your outputting rows of information on your website, alternating the background colour can make the information easier to read for your visitors.

Before CCS3 the only way to alternate colours on your HTML tables or divs was to use Javsascript. If you were outputting results from a database such as MySQL you would use .php.

The following script below alternates row colours using CSS3 nth-of-type(odd) and nth-of-type(even)

<style>
.box
{
width:70%;
padding:10px;
margin-bottom:10px;
}

.box:nth-of-type(odd)
{
background:#ccc;
}

.box:nth-of-type(even)
{
background:#eee;
}
</style>

<div class="box">1</div>
<div class="box">2</div>
<div class="box">3</div>
<div class="box">4</div>
<div class="box">5</div>

Click here for a live example