preface

Whether in the usual development or in the interview, CSS priority is the front end development around the problem, there are a lot of information on the Internet. However, some data are not rigorous enough. As a programmer, you have to be realistic. So I decided to cut through the fog.

Style and selector

CSS2 standard describes it as follows:

A selector’s specificity is calculated as follows:

  • count 1 if the declaration is from is a ‘style’ attribute rather than a rule with a selector, 0 otherwise (= a) (In HTML, values of an element’s “style” attribute are style sheet rules. These rules have no selectors, so a=1, b=0, c=0, and d=0.)
  • count the number of ID attributes in the selector (= b)
  • count the number of other attributes and pseudo-classes in the selector (= c)
  • count the number of element names and pseudo-elements in the selector (= d)

The specificity is based only on the form of the selector. In particular, a selector of the form “[id=p33]” is counted as an attribute selector (a=0, b=0, c=1, d=0), even if the id attribute is defined as an “ID” in the source document’s DTD.

Concatenating the four numbers a-b-c-d (in a number system with a large base) gives the specificity.

Combined with the description of the SELECTOR in CSS3 standard:

A selector’s specificity is calculated as follows:

  • count the number of ID selectors in the selector (= a)
  • count the number of class selectors, attributes selectors, and pseudo-classes in the selector (= b)
  • count the number of type selectors and pseudo-elements in the selector (= c)
  • ignore the universal selector

Concatenating the three numbers a-b-c (in a number system with a large base) gives the specificity.

It can be summarized as follows:

  • If the style is defined in style, giveaIf I give 1, I’ll call that 1a=1
  • If the style is defined in an ID selector, count the number of ID selectors, denoted asb
  • If the style is defined in a class selector, property selector, or pseudo-class selector, count the number of selectors, denoted asc
  • If the style is defined in the element type selector, pseudo element selector, count the number of selectors, denoted asd
  • Ignore wildcard selectors

The specificity of the style can then be calculated from the values of A, B, C, and D (the higher the value, the higher the priority).

:is(), :not(), :has() The specificity of these pseudo-classes is determined by the selector it contains :where() has a specificity of 0

Specific calculation rules are a bit like carrying numbers, to name a few:

The selector specificity Simple said
style a=1,b=0,c=0,d=0 1,0,0,0
#btn a=0,b=1,c=0,d=0 0,1,0,0
li.red.level a=0,b=0,c=2,d=1 0,0,2,1
div[data-index=0] a=0,b=0,c=1,d=1 0,0,1,1
ul ol+li a=0,b=0,c=0,d=3 0,0,0,3
* a=0,b=0,c=0,d=0 0,0,0,0

Just like numbers, high numbers have more weight than low numbers. So, if the above is calculated in base 10, the specificity of style is 1000, the specificity of # BTN is 100, li.red. Level is 21, and * is 0.

But in fact, the standard does not specify how many bases to calculate specificity, leaving only a sentence for manufacturers to feel for themselves.

in a number system with a large base

That means you can base it on a larger number.

Wildcard selector priority 0, element type selector 1, class selector 10, ID selector 1000, style higher! Important infinity. I don’t think this is rigorous, because in fact the cumulative specificity of 10 class selectors is not equal to one ID selector.

So how big is “a large base”? Different vendors have different implementations. Probably for performance reasons (the smaller the number of bits stored, the better), early Webkit and Mozilla computated on 8-bit binaries, that is, 256 (2^8), while Opera computated on 16-bit binaries (65536=2^16).

Its source

Mozilla source

The hexadecimal value 0x10000/0x100 is exactly 256.

An experiment was done to successfully override the id selector style with 256 classes. But I guess Wekit made Base bigger, so it doesn’t work on the newer Chrome. I wanted to know what base the CSS priority calculation is now in Chrome, so I tried overwriting the ID selector with 30,000 + class selectors on the latest Chrome, and the page crashed. But you can be sure that this base is bigger.

In theory, no number of element type selectors can have a higher priority than one class selector, and no number of class selectors can have a higher priority than one ID selector.

The CSS4 draft adds the following sentence:

Due to storage limitations, implementations may have limitations on the size of A, B, or C. If so, values higher than the limit must be clamped to that limit, and not overflow.

What I understand to mean is that no matter how many class selectors there are, vendor implementations cannot give it a higher priority than one ID selector.

We don’t have to worry too much about whether the browser CSS priority calculation is based on a value of 256 or greater, because it’s generally impossible to have a limit of 256 class selectors defined consecutively.

At this point, the priority comparison of the selector can be obtained:

Style > id> class = attribute = pseudo-class > element type = pseudo-element > wildcard

! important

Talking about! Before important, let’s start with a few concepts: user Agent style, User style, and author style

  • User Agent style: The default style provided by the browser, such as the words “User Agent Stylesheet” in the upper right corner of the style panel that we often see when debugging styles using Chrome DevTools.

  • Author style: Style provided by the web developer, that is, inline or external CSS style written by front-end development
  • User style: Infrequently used, this is a browser that allows users to import custom stylesheets, supported by Internet Explorer and Firefox, and supported by Chrome via stylish

With that in mind, we’re ready to move on to the topic of this section.

As described by CSS3, the Cascade Sorting Order rules are as follows:

  1. css transition
  2. added! importantUser Agent style
  3. added! importantThe style of the user
  4. added! importantThe author of the style
  5. css animation
  6. Generic author style
  7. Generic user style
  8. Generic User Agent style

The higher the order is, the higher the priority is. Style and selector styles are item 6, so! Important takes precedence over style.

Normally, the author style overrides the User style, but sometimes you need the User style to override the author style. To balance this, introduce the important tag. In general, the author style is not needed! Important.

Other priority rules

  1. With the same specificity, an element’s inheritance style takes precedence over that of its nearest parent element
  2. With the same specificity, a postloaded style overrides a previously loaded style. For example:

Suppose you have an HTML that looks like this:

<! DOCTYPEhtml>
<head>
  <style>
    .load-before {
      width: 50px;
      height: 50px;
      background-color: red;
    }
  </style>
</head>
<body>
  <div class="load-after load-before"></div>
  <script>
    const head  = document.getElementsByTagName('head') [0];
    const link  = document.createElement('link');
    link.rel  = 'stylesheet';
    link.href = '/public/load-after.css'; // background-color: blue
    head.appendChild(link);
  </script>
</body>
Copy the code

.load-before is defined in inline style and loads faster. .load-after is defined in the external CSS and dynamically inserted into the document via script, which is slow to load. .load-before and.load-after define red and blue background colors, respectively. Eventually, the browser will show up in blue, even though the.load-after is a little bit earlier in class=””. So, the priority of a style has nothing to do with the order defined in the code, but rather with the order in which it is loaded to the browser or executed by the browser.

conclusion

Through the analysis of this article, the CSS priority is no different from our previous cognition, or! The most important selector is the style selector, followed by the ID selector, class selector, element type selector, wildcard, etc. In addition, by reading CSS standards and writing simple examples to verify, I have further improved my understanding of CSS priorities.

The resources

  1. Css-tricks.com/precedence-…
  2. www.thebookdesigner.com/2017/02/sty…
  3. zhuanlan.zhihu.com/p/41604775
  4. www.w3.org/TR/css-styl…
  5. www.w3.org/TR/selector…
  6. www.w3.org/TR/css-casc…
  7. www.w3.org/TR/selector…
  8. Stackoverflow.com/questions/1…​
  9. Ryanseddon.com/css/extreme…​
  10. News.ycombinator.com/item?id=438…​
  11. www.smashingmagazine.com/2007/07/css…
  12. Juicystudio.com/article/sel…
  13. Stackoverflow.com/questions/2…
  14. Stackoverflow.com/questions/1…
  15. www.thoughtco.com/user-style-…