using text-align center in colgroup

Sander picture Sander · Aug 6, 2009 · Viewed 35.3k times · Source

i have a table in my page, i use colgroups to format all cells in this column the same way, works good for background color and all. but cannot seem to figure out why text-align center does not work. it does not align the text centered.

example:

<table id="myTable" cellspacing="5">
    <colgroup id="names"></colgroup>
    <colgroup id="col20" class="datacol"></colgroup>
    <colgroup id="col19" class="datacol"></colgroup>
    <colgroup id="col18" class="datacol"></colgroup>

    <thead>
        <th>&nbsp;</th>
        <th>20</th>
        <th>19</th>
        <th>18</th>
    </thead>
    <tbody>
        <tr>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
        </tr>
    </tbody>
</table>

CSS:

#names {
    width: 200px;
}

#myTable .datacol {
    text-align: center;
    background-color: red;
}

Answer

mercator picture mercator · Aug 6, 2009

Only a limited set of CSS properties applies to columns, and text-align isn't one of them.

See "The mystery of why only four properties apply to table columns" for a description of why this is the case.

In your simple example, the easiest way to fix it would be to add these rules:

#myTable tbody td { text-align: center }
#myTable tbody td:first-child { text-align: left }

That would center all table cells, except the first column. This doesn't work in IE6, but in IE6 the text-align does actually (wrongly) work on the column. I don't know if IE6 supports all properties, or just a larger subset.

Oh, and your HTML is invalid. <thead> misses a <tr>.