如何在第n个子选择器上匹配类选择器

时间:2015-01-30 01:15:56

标签: html css angularjs

我有一个标准的表元素,其中的行由Angular动态生成。该页面如下所示:

<table class="myDataGrid">
    <thead>
        <tr>
            <th>In Service</th>
            ....
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="item in data" ng-class="{'offline': item.InService}">
            <td>{{item.InService}}</td>
            ...
        </tr>
    </tbody>
</table>

现在,我有两个简单的CSS选择器来设置我的行背景颜色:

.myDataGrid tbody tr 
{
    background-color:black;
}

.myDataGrid tbody tr:nth-child(2n + 1)
{
    background-color:gray;
}

一切都很好,行在灰色和黑色之间交替。然而,&#34;离线&#34;添加时忽略class:

.offline
{
    background-color: darkred;
}

它显示在检查器树中,但被第一个类/选择器

覆盖

所以我添加了一些特异性:

.myDataGrid .offline
{
    background-color: darkred;
}

这适用于黑色行(选择器.myDataGrid tbody tr),但对于灰色行根本不起作用,它仍然被取代。

那么,我可以编写哪个选择器使其适用于灰色行?我试过了:

.myDataGrid .offline tbody tr:nth-child(2n + 1)

.myDataGrid tbody tr:nth-child(2n + 1) .offline

无济于事。事实上,它似乎没有匹配它们(它没有出现在检查员列表中)。

1 个答案:

答案 0 :(得分:2)

您需要摆脱tr:nth-child.offline之间的空格,因为离线类已应用于tr,而不是其中一个子类。

.myDataGrid tbody tr:nth-child(2n + 1).offline

.myDataGrid tbody tr.offline:nth-child(2n + 1)