paperlined.org
dev > web > formats > html
document updated 15 years ago, on Nov 17, 2008

Column styling

There are two ways to do per-column styling. One is to use col/colgroup.[1][2] This works on all modern browsers. However, it has several limitations.

Some of these problems occur because HTML is inherently not designed to be "cascading". Notably, a CSS selector like col.c2 td doesn't work (and td.c2 is invalid).

<style>
    col.c1 { background-color:red }
    col.c2 { background-color:green }
    col.c3 { background-color:blue }
</style>

<table>
    <colgroup>
        <col class="c1" />
        <col class="c2" />
        <col class="c3" />
    </colgroup>
    <tr>
        <td>will be red</td>
        <td>will be green</td>
        <td>will be blue</td>
    </tr>
</table>

A better way is to use CSS3's :nth-child() syntax. This works better in numerous ways. However, it's not yet supported on most major browsers.

<style>
    td:nth-child(1) { background-color:red }
    td:nth-child(2) { background-color:green }
    td:nth-child(3) { background-color:blue }
</style>

<table>
    <tr>
        <td>will be red</td>
        <td>will be green</td>
        <td>will be blue</td>
    </tr>
</table>
BUT we can use jQuery to make all the advantages of :nth-child() work in every browser:
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript"> 
    $(document).ready(function() {
        $("td:nth-child(2)").addClass("c2");
        // alternatively
        $("td:nth-child(2)").css("background-color", "red");
    });
</script>