tags:

views:

520

answers:

2

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;
}
+7  A: 

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>. You should probably either move those <th>s into a row in <tbody>, or turn them into <td>s inside a row in the <thead>.

mercator
so you are saying it just is not possible and he only way to achieve this would be to do it on the TD element itself then
Sander
Yep. I've added a fix for your example, though that's not going to work if the table gets any more complicated. DisgruntledGoat provides a few more solutions.
mercator
+3  A: 

See similar question: Why is styling table columns not allowed?

You are only allowed to set border, background, width and visibility properties, due to the fact that cells aren't direct descendents of columns, only of rows.

There are a few solutions. The simplest is to add a class to each cell in the column. Unfortunately that means more HTML but shouldn't bee a problem if you're generating tables from a database etc.

Another solution for modern browsers (i.e. not IE6) is to use some pseudo classes. tr > td:first-child will select the first cell in a row. Opera, Safari, Chrome and Firefox 3.5 also support the :nth-child(n) selector so you can target specific columns.

You could also use td+td to select from the second column onwards (it actually means "select all td elements that have one td element to its left). td+td+td selects from the third column - you can continue in this fashion, overriding properties. Honestly though, it's not great code.

DisgruntledGoat