使用CSS的表列样式

LCJ*_*LCJ 3 html javascript css jquery

我有以下HTML表格.我需要为每列提供背景颜色(第一列=红色,第二列=黄色,第三列=蓝色).我怎么能用CSS做到这一点?

注意:这需要在IE6以后工作.

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>
Run Code Online (Sandbox Code Playgroud)

编辑:

我通过将js代码放在document.ready中来实现它.感谢@Jose Rui Santos http://jsfiddle.net/Lijo/kw4yU/11/

另一个解决方案是http://jsfiddle.net/Lijo/kw4yU/12/

另一种方法:列宽设置 - HTML表

Jos*_*tos 8

使用+选择器

?#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;
}
Run Code Online (Sandbox Code Playgroud)

这里演示

编辑

上述CSS仅更改数据单元格的背景颜色.如果您还想包含表头,请执行以下操作:

#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;
}
Run Code Online (Sandbox Code Playgroud)

EDIT2

一个javascript解决方案是使用jQuery

$("#myTable th, #myTable td").each(function (i) {
    $(this).css('background-color', ['red', 'yellow', 'blue'][i % 3]);
});
Run Code Online (Sandbox Code Playgroud)


Nic*_*lin 5

你可以这样做:

td:nth-child(1){
    background-color: #f00;
}
td:nth-child(2){
    background-color: #ff0;
}
td:nth-child(3){
    background-color: #00f;
}
Run Code Online (Sandbox Code Playgroud)

但是,这是使用CSS3,因此如果您想支持旧版浏览器,则需要使用JavaScript.

  • 请参阅[nth-child]上的[quirksmode compatability table](http://www.quirksmode.org/css/contents.html#t38),以确定您希望支持的浏览器是否支持它. (2认同)