Table header cells ( th ) in different background color in CSS

user4549111 picture user4549111 · Feb 19, 2015 · Viewed 26.5k times · Source

I have following CSS style to show table data in proper format , but I want to display alternate background of table header ( th ) in different color...

How can I modify only below CSS to achieve the same i.e every TH3,TH5 should have blue background ( except the first one TH1 - it will have default background of red ) while TH2,TH4,TH6 should have yellow background.

I have already tried nth child selector and somewhere I read about th+th both ways are not working.

 <style type="text/css">
    table {
           /*...all table attributes like fontsize etc*/
            font-size:11px;
            color:#333333;                
    }
    table th {
            /*...all th attributes like padding etc*/
            background-color:#d4e3e5;
            padding: 8px;
    }
    table td {
            /*...all td attributes like padding etc*/
            padding: 8px;
    }
    </style>

Thanks for all reespons but nth child selector is not working and I have alerdy tried that. Is there any basic way to modify the CSS and achieve the same?

Answer

Gibbs picture Gibbs · Feb 19, 2015

fiddle

nth-child is working.

 th:nth-child(odd) {
     background-color:red; // Replace it with your desired color
 }

 th:nth-child(even) {
     background-color: yellow;
 }

If you have problems furhter, post your HTML and CSS.