表头单元格(th)在CSS中的不同背景颜色

时间:2015-02-19 04:28:12

标签: css css3 tableheader

我有以下CSS样式以正确的格式显示表格数据,但我想以不同的颜色显示表格标题(th)的替代背景...

如何仅在CSS下面修改才能实现相同目的 即每个TH3,TH5应该有蓝色背景(除了第一个TH1 - 它将具有红色的默认背景) 而TH2,TH4,TH6应该有黄色背景。

我已经尝试过第n个孩子选择器,而且我读到了某个地方,这两种方式都没有用。

 <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>

感谢所有的reespons,但是第n个儿童选择器不能正常工作,我有alerdy试过了。是否有任何基本的方法来修改CSS并实现相同的目标?

3 个答案:

答案 0 :(得分:0)

试试这个。,

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

&#13;
&#13;
<!DOCTYPE html>
<html>
<head>
<style>
th:nth-child(odd){ background-color:blue; }
th:nth-child(even){ background-color:yellow; }
</style>
</head>
<body>

<table>
  <tr>
    <th>heading</th>
    <th>heading1</th>
  </tr>
  <tr>
    <td>xxx</td>
    <td>yyy</td>
  </tr>
  <tr>
    <td>xxx1</td>
    <td>yyy1</td>
  </tr>
</table>

</body>
</html>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

fiddle

n-child正在工作

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

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

如果您遇到问题,请发布您的html和css

答案 2 :(得分:0)

你也可以尝试这个

table th:odd
{
       background-color:#000; //Replace it with your desired color
}

table th:odd
{
       background-color:#f00; //Replace it with your desired color
}

or you can try selecting of nth element

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