How to style each table cell in a column through CSS?
I have a regular HTML table:
<table> <tr> <td class="first-column-style">FAT</td> <td>...</td> </tr> <tr> <td class="first-column-style">FAT</td> <td>...</td> </tr> </table> I want to apply a CSS style to each table cell ( td ) in a specific column. Is it possible to do this without applying the class / style attribute to each table cell in this column and without JavaScript?
Use the <col> and style it by following this guide . Thus, you only need to add a class (or an inline style specification) to the <col> element instead of each <td> in the table.
Cautions:
- Any row or cell style replaces a column style.
- The
<col>only supportsborder,background,widthandvisibilitystyles (and their derivatives, such asbackground-color). - The
borderdeclaration does not work if<table>does not haveborder-collapse: collapse;, and the behavior between browsers is incompatible. - The
visibilityad does not work properly in Chrome due to a known bug .
In addition to Sean Patrick Floyd's solution, you can combine :first-child with a neighboring sibling + selector (also not supported by IE6):
td:first-child { /* first column */ } td:first-child + td { /* second column */ } td:first-child + td + td { /* third column */ } /* etc. */ 2015, and based on the response of the first child, but MUCH cleaner.
https://developer.mozilla.org/en-US/docs/Web/CSS/%3Anth-child
td:nth-child(1) { /* first column */ } td:nth-child(2) { /* second column */ } td:nth-child(3) { /* third column */ } Super clean code
Good for the first and last columns, you can use the pseudo-class :first-child and :last-child :
/* make the first cell of every row bold */ tr td:FIRST-CHILD{ font-weight:bold; } /* make the last cell of every row italic */ tr td:LAST-CHILD{ font-style:italic; } Reference:
The following allows you to create columns at the table level and can be used in a more general way for the previous examples, since you do not need to make assumptions about the styles applied to a given column index in the stylesheet itself.
I agree that the <col> approach is best if it meets your needs, but the range of styles is very limited.
Examples of styles for columns 1, 2, and 4 with gray text.
HTML
<table class="example col1-readonly col2-readonly col4-readonly"> CSS
.example.col1-readonly tr td:nth-child(1), .example.col2-readonly tr td:nth-child(2), .example.col3-readonly tr td:nth-child(3), .example.col4-readonly tr td:nth-child(4) { color:#555; } This is an old post. But I had the same question. Found this to work:
<!DOCTYPE html> <html> <head> <style> tr:nth-child(3)>td:nth-child(2){background: red;} </style> </head> <table> <tr><td></td><td>A</td><td>B</td><td>C</td></tr> <tr><td>1</td><td>A1</td><td>B1</td><td>C1</td></tr> <tr><td>2</td><td>A2</td><td>B2</td><td>C2</td></tr> <tr><td>3</td><td>A3</td><td>B3</td><td>C3</td></tr> </table> </html> This style setting sets the background color to red in the third row and second column,