CSS重写规则和特异性 [英] CSS override rules and specificity

查看:88
本文介绍了CSS重写规则和特异性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我经常被CSS覆盖规则困惑:一般来说,我意识到更具体的样式表覆盖较少特定的样式表,并且特定性由指定多少个选择器决定。还有!important 关键字,它也起到了作用。

I'm often confused by CSS override rules: in general, I realize that more specific style-sheets override less specific ones, and that specificity is determined by how many selectors are specified. There's also the !important keyword, which plays a role as well.

这里有一个简单的例子:有一个表有两个表单元格。表本身有一个CSS规则,适用于表中的所有单元格。然而,第二表格单元格具有它自己的规则,其应该覆盖一般表格规则:

So, here's a simple example: I have a table with two table cells. The table itself has a CSS rule which applies to all cells within the table. However, the second table cell has it's own rule which should override the general table rule:

<html>
<head>
<style type = "text/css">

table.rule1 tr td {
    background-color: #ff0000;
}

td.rule2 {
    background-color: #ffff00;
}

</style>

</head>
<body>
    <table class = "rule1">
        <tr>
            <td>abc</td>
        </tr>
        <tr>
            <td class = "rule2">abc</td>
        </tr>
    </table>
</body>
</html>

但是...当我在浏览器中打开这个,我看到 rule2 不会覆盖 rule1 。好吧,所以我想我需要使 rule2 更多特定,但我不能真正定义任何进一步的选择器,因为我只是想把它应用到一个特定的表格。所以,我试着把!重要关键字,但不起作用。

But... when I open this in a browser, I see that rule2 doesn't override rule1. Okay - so I guess I need to make rule2 more "specific", but I can't really define any further selectors since I just want to apply it to a particular table cell. So, I tried putting the ! important keyword, but that doesn't work either.

我可以覆盖 rule2 如果我在< div> 中包装文本节点,如:

I'm able to override rule2 if I wrap the text node in a <div>, like:

        <td class = "rule2"><div>abc</div></td>

...然后使CSS规则更具体:

...and then make the CSS rule more specific:

td.rule2 div {
    background-color: #ffff00; !important
}

这可行,但它不是我想要的。首先,我想将规则应用到表单元格,而不是DIV。它有所不同,因为您仍然可以看到 rule1 作为div周围的边框的背景颜色。

This works, but it's not exactly what I want. For one thing, I want to apply the rule to the table cell, not the DIV. It makes a difference because you can still see the background color of rule1 as a border around the div.

,我需要做什么来告诉CSS我想让 rule2 覆盖 rule1 td 元素?

So, what do I need to do to tell CSS I want rule2 to override rule1 for the td element?

推荐答案

为了给第二个规则更高的特异性,规则。在这种情况下,我将从规则1添加 table.rule1 tr 并将其添加到规则二。

To give the second rule higher specificity you can always use parts of the first rule. In this case I would add table.rule1 trfrom rule one and add it to rule two.

table.rule1 tr td {
    background-color: #ff0000;
}

table.rule1 tr td.rule2 {
    background-color: #ffff00;
}

过了一会儿我发现这很自然,但我知道有些人不同意。对于这些人,我建议您查看 LESS SASS

After a while I find this gets natural, but I know some people disagree. For those people I would suggest looking into LESS or SASS.

这篇关于CSS重写规则和特异性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆