CSS样式优先级

5
我遇到了CSS声明优先级的问题。我的页面包含一个外部CSS文件和一些内联CSS声明,它们应该会覆盖掉那个规则。据我所知,内联样式声明应该会覆盖外部CSS声明。然而,当我在Chrome中查看页面时,表格的第二行显示为蓝色,而不是根据内部样式声明定义的红色。
我在哪里出错了?
以下是HTML代码:
<html>
<head>
    <link rel="stylesheet" href="screen.css" type="text/css" media="screen, projection">
    <style type="text/css">
        td,tr,th
        {
            background: Red;
        }
    </style>
</head>
<body>
    <table>
        <tr>
            <td>11</td>
            <td>22</td>
        </tr>
        <tr>
            <td>aa</td>
            <td>bb</td>
        </tr>
    </table>
</body>
</html>

这是CSS文件的内容:
tbody tr:nth-child(even) td,
tbody tr.even td
{
    background: #e5ecf9;
}

你应该避免使用!important - 参见https://dev59.com/FHA65IYBdhLWcg3wqAWt - andyb
2个回答

16

在计算哪个规则具有最高特异性时,选择器的数量很重要。

CSS特异性的两个优秀可视化工具是http://www.standardista.com/css3/css-specificity/http://www.stuffandnonsense.co.uk/archives/css_specificity_wars.html

您应该避免仅将!important附加到规则上以进行覆盖(请参见What are the implications of using "!important" in CSS?),而应更改选择器以使您的规则具有与导入规则相同或更大的权重。

例如,以下内容将使所有单元格background:red

thead tr:nth-child(1n) th, tbody tr:nth-child(1n) td {
    background:red;
}

@Raisch 是的,谢谢。我发现了,只是在本地测试正确的选择器 :-) - andyb

2
在这种情况下,更详细的规则会生效。
在你的HTML中尝试以下内容:
<style type="text/css" media="screen, projection">
    tbody tr:nth-child(even) td,
    tbody tr:nth-child(even) tr,
    tbody tr:nth-child(even) th
    {
        background: Red;
    }
</style>

敬礼


2
代码具有误导性,因为部分,tr,th没有影响,其作用很容易被误解。重要的是使用足够大的特异性设置某些td元素。 - Jukka K. Korpela
@JukkaK.Korpela - 我知道,我只是扩展了他自己的CSS块。 :-) - Raisch
@JukkaK.Korpela在6年后更新了我的答案! :-) - Raisch

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接