Home > Enterprise >  Why is an eleven-class selector not trumping a single id?
Why is an eleven-class selector not trumping a single id?

Time:02-12

I have an example of a selector with 11 classes. According to W3Schools, a class is worth 10 points, meaning that 11 classes should clearly trump a single id. Why is it not doing so in this case? The selector is correct and only applies the blue colour when adding !important.

The code:

#test { color: red } /* 100 points */
div .test { color: green } /* 11 points */
.test1.test2.test3.test4.test5.test6.test7.test8.test9.test10.test11 {
  color: blue; /* works with !important */
} /* not 110 points? */
p { color: orange } /* 1 point */
<div>
    <p id='test' class='test1 test2 test3 test4 test5 test6 test7 test8 test9 test10 test11'>Test</p>
</div>

Are W3Schools wrong or am I missing something?

CodePudding user response:

You can refer to this CSS-tricks article (doc). Which explains this properly.

To summarize this in short. Basically, The point system is just a way to help you remember the specificity of the elements which are like below.

inline > id > class >elements

As mentioned in the article, It tells CSS applies vastly different specificity weights to classes and IDs. In fact, an ID has infinitely more specificity value! That is, no amount of classes alone can outweigh an ID.

Also, Keep in mind the only exception to this rule is the usage of !important which will override the inline styles.

  • Related