user2571510
user2571510

Reputation: 11377

Apply table style to all columns except first column

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.

Upvotes: 9

Views: 9734

Answers (2)

Jukka K. Korpela
Jukka K. Korpela

Reputation: 201538

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.

Upvotes: 17

codingrose
codingrose

Reputation: 15699

Try this:

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

Here is the fiddle.

Upvotes: 16

Related Questions