1

为什么这两个不相等?第一个显示绿色行,而第二个没有。唯一的区别在于 html c 此外,nth-child 选择器的特殊性是什么?

<!DOCTYPE html>
<html>
    <head>
        <title>Stripe Test</title>
        <style type='text/css'>
            tr:nth-child(2n+1)
            {
                background-color: red;
            }
            tr.c
            {
                background-color: green;
            }
        </style>
    </head>
    <body>
        <table class='stripe'>
            <tr class='c'>
                <td>one</td>
            </tr>
            <tr>
                <td>two</td>
            </tr>
            <tr>
                <td>three</td>
            </tr>
        </table>
    </body>
</html>

-对-

<!DOCTYPE html>
<html>
    <head>
        <title>Stripe Test</title>
        <style type='text/css'>
            tr:nth-child(2n+1)
            {
                background-color: red;
            }
            tr .c
            {
                background-color: green;
            }
        </style>
    </head>
    <body>
        <table class='stripe'>
            <tr class='c'>
                <td>one</td>
            </tr>
            <tr>
                <td>two</td>
            </tr>
            <tr>
                <td>three</td>
            </tr>
        </table>
    </body>
</html>
4

3 回答 3

2

第二个是完全不同的选择器。tr .c中间有一个空格会查找类名为“c”且具有祖先元素的<tr>元素。第一个tr.c查找<tr>具有类名“c”的元素。

这与特定性无关,而是您对 CSS 的理解。

于 2012-05-01T04:58:45.123 回答
1

tr.c(无空格)` 是 c 类的表行。

tr .c(带空格)是一个表格行,后跟一些其他未指定的 c 类标签。

该空间意味着父/子关系。由于您已经在 tr 标签本身上设置了c,因此在 tr 下方没有具有类的子级。trc

于 2012-05-01T04:59:15.413 回答
-1

考虑改用 :nth-child(odd) ,还要注意 IE 根本不喜欢它。

于 2012-05-01T05:02:29.187 回答