Before talking about CSS priority, we need to understand what CSS is and what it is used for.
First, let’s give a brief explanation of CSS: CSS is the abbreviation of Cascading Style Sheets. Its specifications represent a unique stage of development in the history of the Internet. Nowadays, for friends who are engaged in web page production, there should be few who have not heard of CSS, because we often need to use it in the process of making web pages.
Secondly: We can set a rich and easy-to-modify appearance for the document through CSS to reduce the work burden of web page producers, thereby reducing the cost of production and post-maintenance.
In fact, it is completely redundant to talk about what CSS is and what its functions are. I believe that friends who are engaged in web page production have already been exposed to it more or less.
Closer to home, let’s get into today’s topic:
1. What is CSS priority?
The so-called CSS priority refers to the order in which CSS styles are parsed in the browser.
2. CSS priority rules
Since styles have priority, there will be a rule to agree on this priority, and this "rule" is the focus of this article.
Specificity in a style sheet describes the relative weight of different rules. Its basic rules are:
Finally, write the three numbers in the correct order without adding spaces or commas to get a three-digit number (css2.1 uses 4 digits). (Note that you need to convert the number to a larger number ending in three digits). The final list of numbers corresponding to the selector makes it easy to determine which features of the higher number override those of the lower number.
For example:
3. Selector list for feature classification
Here is a list of selectors sorted by attribute:
Selector | Characteristic value |
h1 {color:blue;} | 1 |
p em {color:purple;} | 2 |
.apple {color:red;} | 10 |
p.bright {color:yellow;} | 11 |
p.bright em.dark {color:brown;} | twenty two |
#id316 {color:yellow} | 100 |
Judging from the above table alone, it seems difficult to understand. Here is another table:
Selector | Characteristic value |
h1 {color:blue;} | 1 |
p em {color:purple;} | 1+1=2 |
.apple {color:red;} | 10 |
p.bright {color:yellow;} | 1+10=11 |
p.bright em.dark {color:brown;} | 1+10+1+10=22 |
#id316 {color:yellow} | 100 |
From the above, it can be easily seen that the weight of the HTML tag is 1, the weight of CLASS is 10, the weight of ID is 100, and the inherited weight is 0 (will be discussed later).
Add the strings of numbers bit by bit according to these rules to get the final weight, and then compare them bit by bit from left to right when comparing and choosing.
The priority issue is actually a conflict resolution issue. When the same element (content) is selected by the CSS selector, different CSS rules must be chosen according to the priority. There are actually many issues involved.
Having said that, we have to talk about the inheritance of CSS.