155

Using css only, how can I override the css of only the 2nd column of a table.

I can get to all of the columns using:

.countTable table table td

I can not get to the html on this page to modify it since it is not my site.

Thanks.

5 Answers5

283

You can use the :nth-child pseudo class like this:

.countTable table table td:nth-child(2)

Note though, this won't work in older browsers (or IE), you'll need to give the cells a class or use javascript in that case.

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
28

Try this:

.countTable table tr td:first-child + td

You could also reiterate in order to style the others columns:

.countTable table tr td:first-child + td + td {...} /* third column */
.countTable table tr td:first-child + td + td + td {...} /* fourth column */
.countTable table tr td:first-child + td + td + td +td {...} /* fifth column */
Marco Panichi
  • 1,068
  • 1
  • 18
  • 31
  • 1
    I opted for this in a situation where the owners of the site maintaining the code were not developers and this gave them the ability to change the alignment of columns in their data tables in a very straight forward way that although a little verbose, with comment like you have here, made it easy for them to know which selector block was for which column from the left. Again not the most elegant and efficient way, but it worked! – Eric Bishard May 19 '17 at 22:30
20

To change only the second column of a table use the following:

General Case:

table td + td{  /* this will go to the 2nd column of a table directly */

background:red

}

Your case:

.countTable table table td + td{ 

background: red

}

Note: this works for all browsers (Modern and old ones) that's why I added my answer to an old question

Satish Sharma
  • 9,547
  • 6
  • 29
  • 51
Abzoozy
  • 874
  • 12
  • 26
  • What would be the tweak to just select the first column? Using table td { ... } selects all cells in other columns as well. – j4v1 Jun 17 '15 at 20:35
  • 1
    @j4v1 table td { background: red;} // first column will have red background table td + td { background: blue;} // rest will have blue – Abzoozy Jul 25 '15 at 11:21
-2

on this web http://quirksmode.org/css/css2/columns.html i found that easy way

<table>
<col style="background-color: #6374AB; color: #ffffff" />
<col span="2" style="background-color: #07B133; color: #ffffff;" />
<tr>..
CodexVarg
  • 502
  • 1
  • 6
  • 20
-3

You could designate a class for each cell in the second column.

<table>
<tr><td>Column 1</td><td class="col2">Col 2</td></tr>
<tr><td>Column 1</td><td class="col2">Col 2</td></tr>
<tr><td>Column 1</td><td class="col2">Col 2</td></tr>
<tr><td>Column 1</td><td class="col2">Col 2</td></tr>
</table>
Duniyadnd
  • 4,013
  • 1
  • 22
  • 29
  • I can't use this. Like I said, this isn't my page and so, I can't change the html. –  Mar 29 '10 at 00:19
  • 2
    @Duniyadnd this is not a good approach, compared to existing way of using selectors. – P.M Dec 19 '12 at 19:41