从N开始的颜色表列(td:nth-​​of-type)

时间:2013-01-23 09:36:07

标签: html css css3 css-selectors css-tables

我想从某一列开始添加某种背景颜色。而不是必须为每列使用css类,我宁愿在可能的情况下这样做。

我将拥有一个包含数百行和大约25列的巨大表格,我更愿意避免使用不必要的代码。

目前,我使用td:nth-of-type属性来执行此操作:

.demo tr.selectedRow td:nth-of-type(9),
.demo tr.selectedRow td:nth-of-type(10),
.demo tr.selectedRow td:nth-of-type(11),
.demo tr.selectedRow td:nth-of-type(12),
.demo tr.selectedRow td:nth-of-type(13),
.demo tr.selectedRow td:nth-of-type(14),
.demo tr.selectedRow td:nth-of-type(15),
.demo tr.selectedRow td:nth-of-type(16){
    background-color:#fff16b;
}

我想知道是否有任何方法可以减少这种情况。

The documentation并没有多说......

2 个答案:

答案 0 :(得分:8)

http://css-tricks.com/examples/nth-child-tester/此测试人员可以提供帮助。看起来您想在9之后选择所有内容,因此请使用下面的代码

选择除First 8之外的每个TD

.demo tr.selectedRow td:nth-child(n+9) {
    color: red;   
}

答案 1 :(得分:0)

如果八个人之后的每一栏都没有为前八个人提供课程,而其他人则没有。如果所有其余部分当然应该是相同的,那么这将起作用。

这甚至适用于IE浏览器。

使用colgroup

的示例
<html>
    <head>
        <title>Title</title>
        <style>
            .colSpecial {background-color: #fee;}
            .colDefault {background-color: #fff; border: 1px solid black;}
            tr:hover {background-color: #efe;}
        </style>
    </head>
    <body>
        <table>
            <colgroup>
                <col class="colDefault" />
                <col class="colDefault" />
                <col class="colDefault" />
                <col class="colDefault" />
                <col class="colDefault" />
                <col class="colDefault" />
                <col class="colDefault" />
                <col class="colDefault" />
                <col class="colSpecial" />
                <col class="colSpecial" />
                <col class="colSpecial" />
                <col class="colSpecial" />
                <col class="colSpecial" />
                <col class="colSpecial" />
                <col class="colSpecial" />
            </colgroup>
            <tr>
                <td>Data</td>
                <td>Data</td>
                <td>Data</td>
                <td>Data</td>
                <td>Data</td>
                <td>Data</td>
                <td>Data</td>
                <td>Data</td>
                <td>Data</td>
                <td>Data</td>
                <td>Data</td>
                <td>Data</td>
                <td>Data</td>
                <td>Data</td>
                <td>Data</td>
            </tr>
        </table>
    </body>
</html>