Coloring Columns and Rows on Tables with CSS3 and RGBA

Tables still have their place in the web development world. The best use for them is to display data in a grid, like for reports. I'd like to show a quick example of how to color the columns and rows using CSS3 with rgba. I won't show the full source code on the blog, but you can easily view the source of the example page.

Stripe Table columns and Rows with CSS and RGBA

Lets start with our html. For this table example we may be using a few tags you aren't very familiar with: thead, tbody, col. Here is a snippet of our html to create the table (I've cut out a bunch of the table rows just to shorten it up.

<table cellpadding="0" cellspacing="0" class="stripeTable"> 
    <col class="col0"> 
    <col class="col1"> 
    <col class="col0"> 
    <col class="col1"> 
    <col class="col0"> 
            <th>Qtr 1</th> 
            <th>Qtr 2</th> 
            <th>Qtr 3</th> 
            <th>Qtr 4</th> 
        <tr class="bg0"> 
        <tr class="bg1"> 

You see there is a corresponding column with each column in the row. These span vertically the height of the table, underneath each table row and cell. We can assign styles to these but the only problem is we can't see the styles because the coloring of tr and td overlays them. The solution? Use rgba for background colors of your tr. Here would be our css for our table rows:

.stripeTable tbody tr.bg0{  background-color: rgba(244,244,244, .7); }
.stripeTable tbody tr.bg1{ background-color: rgba(255,255,255, .7); }

That should give us some alternating row colors. If you're not familiar with rgba, it resembles rgb, except one more parameter for opacity. Now lets style our columns:

.stripeTable .col0{ background-color: #cfcfcf; }
.stripeTable .col1{ background-color: #ffffff; }

We use a solid color for columns to be sure they are strong and show through. Now, this should pretty well work for the most part, but don't we all like to highlight rows of a table as we hover over them? Lets do that with the help of some pseudo class selectors:

.stripeTable tbody tr.bg0:hover{ background-color: rgba(255, 191, 85, .7); }
.stripeTable tbody tr.bg1:hover{ background-color: rgba(255, 191, 85, .7); }

And now the final part, just for fun, lets highlight our first column, because it could have some important data in it. We'll do this with the first-child pseudo selector:

.stripeTable col:first-child{ background-color: #FfBf55; }

This all works pretty well with our browsers that support CSS3 fairly well, Chrome, Firefox, but IE as always has a hard time with it.

View the Demo