【问题标题】:Why can't I beat an ID with multiple classes? [duplicate]为什么我不能用多个类打败一个 ID? [复制]
【发布时间】:2012-03-21 08:55:37
【问题描述】:

可能重复:
Points in CSS specificity

这是我的意思的一个例子:

http://jsfiddle.net/BTJXt/9/

不知何故,1 个 ID 将击败看似无限数量的课程。这是如何计算的?

<style>
    div {
    height:200px;
    width:200px;
    }

    #big .little {
    /* Specificy value = 110 */
    background-color:red;
    }

     #big .little.little {
    /* Specificy value = 120 */
    background-color:blue;
    }

    .little.little.little.little.little.little.little.little.little.little.little.little.little {
    /* Specificy value = 130, why doesn't this win? */
    background-color:green;
    }


</style>   

<div id="big">
    <div class="little"></div>
</div>​

【问题讨论】:

标签: css css-selectors css-specificity


【解决方案1】:

简单地说:一个 ID 总能击败任意数量的类、伪类、属性选择器或类型选择器,但不一定是另一个 ID。这就是您需要记住的全部内容。

或者深入了解技术细节:特异性不计入我们都使用的一些十进制数字基数。 ID 不值“100 分”,类/属性/伪类不是“10 分”,类型/伪元素不是“1 分”,等等。您不要将这些数字相加并在数学上进行比较, 基于它们的 sum;这不是它的工作原理。 (您确实将单独的 ID 数量、类/属性/伪类的数量等相加,但您不会将所有单独的数字相加。)

这些简单选择器的特殊性以完全不同的方式计算。 spec 说得最好:

9。计算选择器的特异性

选择器的特异性计算如下:

  • 统计选择器中 ID 选择器的数量 (= a)
  • 统计选择器中类选择器、属性选择器和伪类的数量 (= b)
  • 统计选择器中类型选择器和伪元素的数量(= c)
  • 忽略通用选择器

negation pseudo-class 中的选择器与其他选择器一样计算,但否定本身不计为伪类。

连接三个数字 a-b-c(在具有大基数的数字系统中)给出了特异性。

例子:

*               /* a=0 b=0 c=0 -> specificity =   0 */
LI              /* a=0 b=0 c=1 -> specificity =   1 */
UL LI           /* a=0 b=0 c=2 -> specificity =   2 */
UL OL+LI        /* a=0 b=0 c=3 -> specificity =   3 */
H1 + *[REL=up]  /* a=0 b=1 c=1 -> specificity =  11 */
UL OL LI.red    /* a=0 b=1 c=3 -> specificity =  13 */
LI.red.level    /* a=0 b=2 c=1 -> specificity =  21 */
#x34y           /* a=1 b=0 c=0 -> specificity = 100 */
#s12:not(FOO)   /* a=1 b=0 c=1 -> specificity = 101 */

注意它说的是“连接”(如将字符串连接在一起),而不是“添加”(如算术意义上的 2 + 2 = 4)。

还请注意,它说的是“具有大基数的数字系统”;这只是为了说明您不要将这些特异性分数视为十进制数,其中 13 × 10 = 130 大于 1 × 100 = 100。

这是计算选择器特异性的方法:

/* 1 ID, 1 class     -> specificity = 1-1-0 */
#big .little

/* 1 ID, 2 classes   -> specificity = 1-2-0 */
#big .little.little

/* 0 IDs, 13 classes -> specificity = 0-13-0 */
.little.little.little.little.little.little.little.little.little.little.little.little.little

现在请注意第三个选择器的特异性比前两个选择器,因为没有使用 ID 选择器?

比较其他两个选择器时,它们都有一个 ID 选择器,您会看到第二个选择器多了一个类。在这种情况下,由于额外的类选择器,第二个选择器获胜,即使每个选择器都有一个 ID 选择器,因为 ID 选择器他们自己共享相同的特异性。

【讨论】:

  • 哇,很棒的解释,谢谢!
猜你喜欢
  • 1970-01-01
  • 2019-08-10
  • 2010-10-08
  • 1970-01-01
  • 2015-06-28
  • 2016-06-20
  • 2019-03-08
  • 2013-05-02
  • 2017-03-23
相关资源
最近更新 更多