문제

I have been following this article on CSS specifity. It assigns values to selectors and the selector with the highest sum of values will have precedence.

An id has a value of 100. a class has a value of 10.

My problem is in this example I tried.

HTML

<div id="id" class="a b c d e f g h i j k l">What color?</div>

CSS

/* calculated specificity: 100 */
#id{
    color:red;
}

/* calculated specificity: 120 */
.a.b.c.d.e.f.g.h.i.j.k.l{
    color:green;
}

I expected the div to be green since 12 classes would have a value of 120. But it is red when I run it. Is there a problem with my calculation?

DEMO

도움이 되었습니까?

해결책

ID trumps class specificity as MDN states:

The following list of selectors is by increasing specificity:

  • Universal selectors
  • Type selectors
  • Class selectors
  • Attributes selectors
  • Pseudo-classes
  • ID selectors
  • Inline style

The specificity calculation can be a bit confusing, but you need to remember, as the W3 states, that when calculating the specificity that you concatenate, not add the numbers together.

So for example:

  • #id has a specificity = 0,1,0,0
  • .a.b.c.d.e.f.g.h.i.j.k.l has a specificity = 0,0,12,0

So yes, the ID will trump the pure class selection every time.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top