9
votes

I am creating an HTML table dynamically with JavaScript so that the number of columns can vary (between 1 and 10). Is there a way in CSS that I can automatically apply a class style to all columns of this table except the first column without having to add a class manually to each column ?

I thought maybe there is a trick with using the nth-child but couldn't get this working.

2
you can use the default style for the table cells and later override the style of the first column td:first-childbansi

2 Answers

15
votes

There are several ways. One of them is

th:nth-child(n+2), td:nth-child(n+2) { ... }

A different one:

th + th, th + td, td + th, td + td { ... }

The browser coverage for these is good, but not quite 100%. To cover all CSS-enabled browsers, I’m afraid you would need to do this indirectly:

th, td { /* your settings here */ }
th:first-child, td:first-child { /* “overwriting” settings here */ }

Here “overwriting settings” mean settings that override the settings in the first rule. But this requires information about the desired rendering for the first column.

11
votes

Try this:

td:not(:first-child){color:green;}

Here is the fiddle.