Is there a way to set the text alignment of entire column in a table?

Is there a simple way to set the text alignment of all cells in the second column to right?

Or is the only way is to set the alignment for each cell in the column?

(Unfortunately, the align attribute of the col tag is not supported in Firefox.)


Solution 1:

Add a class to every cell in the 2nd column.

.second {
   text-align: right;
}

You could also use CSS3.

tr td:nth-child(2) { /* I don't think they are 0 based */
   text-align: right;
}

(It won't work in <= IE8)

Solution 2:

While not particularly elegant, I like to toss something like this in my site-wide css file:

.tr1 td:nth-child(1), .tr1 th:nth-child(1),
.tr2 td:nth-child(2), .tr2 th:nth-child(2),
.tr3 td:nth-child(3), .tr3 th:nth-child(3),
.tr4 td:nth-child(4), .tr4 th:nth-child(4),
.tr5 td:nth-child(5), .tr5 th:nth-child(5),
.tr6 td:nth-child(6), .tr6 th:nth-child(6),
.tr7 td:nth-child(7), .tr7 th:nth-child(7),
.tr8 td:nth-child(8), .tr8 th:nth-child(8),
.tr9 td:nth-child(9), .tr9 th:nth-child(9) { text-align:right }

.tc1 td:nth-child(1), .tc1 th:nth-child(1),
.tc2 td:nth-child(2), .tc2 th:nth-child(2),
.tc3 td:nth-child(3), .tc3 th:nth-child(3),
.tc4 td:nth-child(4), .tc4 th:nth-child(4),
.tc5 td:nth-child(5), .tc5 th:nth-child(5),
.tc6 td:nth-child(6), .tc6 th:nth-child(6),
.tc7 td:nth-child(7), .tc7 th:nth-child(7),
.tc8 td:nth-child(8), .tc8 th:nth-child(8),
.tc9 td:nth-child(9), .tc9 th:nth-child(9) { text-align:center }

Then just specify which column numbers you want center or right aligned, i.e. if you want column 2 & 7 right aligned, and 3 centered, just do:

<table class="tr2 tc3 tr7">

While the CSS isn't super elegant, the alternatives are even less elegant: i.e. a custom class for each table, or requiring each tr to have a class="ralign" or similar.

Doesn't work with IE8