我想在表格列的标题(th)中添加一个CSS类名"currency",并让列中的所有子数据单元格(td)对齐.
我最好的尝试是:
table th.currency td {
text-align: right;
}
Run Code Online (Sandbox Code Playgroud)
然而,这显然不起作用.我试图让它成为直接后代">",但这也不起作用.
我想避免将单独的"货币"类名添加到所有td单元格中.有人有解决方案吗?
如果你知道列号,你可以在表中的所有trs上使用第n个孩子的css选择器.
table tr td:nth-child(n /*this is the column number*/)
{
text-align: right;
}
Run Code Online (Sandbox Code Playgroud)
这是一个jsfiddle
编辑:您还可以为表提供唯一的ID并以这种方式定位它们:
#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;
}
Run Code Online (Sandbox Code Playgroud)
使用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");
});
Run Code Online (Sandbox Code Playgroud)
工作jsFiddle:http: //jsfiddle.net/8XSLF/
如果货币类没有右对齐,则可以使用css函数:
rows.find("td:nth-child(" + (colNumber + 1) + ")").css("text-align","right");
Run Code Online (Sandbox Code Playgroud)
这可以放在许多页面共享的脚本中,但不能仅使用CSS.