Justin
Justin

Reputation: 10897

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?

Upvotes: 3

Views: 9035

Answers (3)

Caleb Doucet
Caleb Doucet

Reputation: 1781

If you know the column number you can use css selector of nth child on all trs in table.

table tr td:nth-child(n /*this is the column number*/)
{
    text-align: right;
}

Here is a jsfiddle

Edit: You could also give the tables unique ids and target them that way:

#table1 tr td:nth-child(3 /*this is the column number*/)
{
    text-align: right;
}
#table2 tr td:nth-child(2 /*this is the column number*/)
{
    text-align: right;
}
#table3 tr td:nth-child(5 /*this is the column number*/)
{
    text-align: right;
}

Upvotes: 7

Fosco
Fosco

Reputation: 38506

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.

Upvotes: 6

Skyrel
Skyrel

Reputation: 226

add comma (,) between table, th, and td ( yours not apply to th and td

Upvotes: -1

Related Questions