CSS特性如何工作? [英] How does the CSS specificity work?
问题描述
我有一些链接的CSS类。可以有人解释下面的代码如何工作吗?它将文本显示为绿色。有人可以解释吗?
I have some CSS classes which are chained. Can some one explain how the following code works? It displays the text as green. Can someone explain?
<html>
<head>
<style>
.a .c {
color: red;
}
.b .c {
color: green;
}
.c {
color: blue;
}
</style>
</head>
<body>
<div class="a">
<div class="b">
<div class="c">
hi
</div>
</div>
</div>
</body>
</html>
推荐答案
第一个说任何一个项目 c
/ code>将显示红色。
The first says that any an item with class c
inside of any item with of class a
will be colored red.
.a .c {
color: red;
}
第二个表示任何一个具有 c
将以绿色着色。它优先于第一条规则,因为它与第一条规则一样深,但之后定义。 b
的任何项目内
The second says that any an item with class c
inside of any item of class b
will be colored green. It takes precedence over the first rule as it is just as deep as the first rule, but defined after that rule.
.b .c {
color: green;
}
这说明任何带有 c
应该是蓝色的。但由于不像上述规则那样具有描述性,因此不优先。如果您有一个类别 c
的不嵌套在类 a
内的项目 b
,则此规则生效。
This says that any item with the class c
should be blue. But since it is not as descriptive as the rules above, it does not take precedence. If you have an item with class c
that is not nested inside a class a
or b
, then this rule will take effect.
.c {
color: blue;
}
因此,有两个规则要记住:
So there are two rules to remember:
- 更具体的规则获得更高的优先级
- 稍后定义的规则比其特定的特定规则获得更高的优先级。 li>
- The more specific rules get higher precedence
- The later defined rules get higher precedence than their just-as-specific counterparts.
这篇关于CSS特性如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!