Table Column Styling using CSS
css, html, javascript, jquery
Solution
Use the `+` selector
#myTable tr td { /* makes all columns red */
background-color: red;
}
#myTable tr td + td { /* makes 2nd and 3rd columns yellow */
background-color: yellow;
}
#myTable tr td + td + td { /* makes 3rd column blue */
background-color: blue;
}
demo here
EDIT
The above CSS only changes background color for the data cells. If you want to include the table headers as well, just do:
#myTable tr th,
#myTable tr td {
background-color: red;
}
#myTable tr th + th,
#myTable tr td + td {
background-color: yellow;
}
#myTable tr th + th + th,
#myTable tr td + td + td {
background-color: blue;
}
EDIT2
One javascript solution is, using jQuery
$("#myTable th, #myTable td").each(function (i) {
$(this).css('background-color', ['red', 'yellow', 'blue'][i % 3]);
});
Problem
I have the following HTML table. I need to give a background color to each column (first column = red, second column = yellow, third column = blue). How can I do this using CSS? Note: This need to work in IE6 onwards. http://jsfiddle.net/Lijo/kw4yU/ ``` <table id = "myTable"> <thead> <tr> <th> Name </th> <th> Address </th> <th> Age </th> </tr> </thead> <tr> <td> Lijo </td> <td> India </td> <td> 27 </td> </tr> </table> ``` EDIT: I got it working by putting the js code inside document.ready. Thanks to @Jose Rui Santos http://jsfiddle.net/Lijo/kw4yU/11/ Another solution is http://jsfiddle.net/Lijo/kw4yU/12/ Yet another approach: Column width setting - HTML table