Justin Justin - 1 month ago 10
CSS Question

CSS Selector for all data rows in a specific column of an html table element

I would like to add a CSS class name "currency" to the header (th) of my table's column and have all the children data cells (td) in the column align to the right.

My best attempt is :

table th.currency td {
text-align: right;
}


However this obviously does NOT work. I tried to make it direct descendants ">" but that didn't work either.

I'd like to avoid adding the individual "currency" class name to ALL the td cells. Anybody got a solution?

Answer

Using jQuery:

$.each($('th.currency'),function(idx,val) {

    var table = $(this).parent().parent();
    var colNumber = $(this).parent("tr").children().index($(this));
    var rows = table.children("tr");
    rows.find("td:nth-child(" + (colNumber + 1) + ")").addClass("currency");

});

Working jsFiddle: http://jsfiddle.net/8XSLF/

If the currency class doesn't right align, you can use the css function instead:

    rows.find("td:nth-child(" + (colNumber + 1) + ")").css("text-align","right");

This can be put in a script shared among many pages, but can't be done with just CSS alone.