As for CSS selector priority, first of all, we need to know that there is a default browser style if the style is not set. For example, Chrome's default font size is 12px. Second, the child element inherits the style of the parent element.Copy the code

Then the priority of CSS selectors is discussed separately


1. If a single selector is directly selected, for example:p {font-size: 20px; }
  • The order of preference of the selectors is: ID selector > Class (pseudo-class) selector > tag (pseudo-element) selector > wildcard * (sibling/child element selector) > Inheritance Style > browser default style
2. In the case of indirect inheritance, as follows
    <style>
       .grandparent{
           font-size: 30px;
       }
       .parent{
           font-size: 18px;
       }
       /* p { font-size: 15px; } * /
    </style>
    

    <div class="grandparent" style="width: 200px; height: 200px;">My grandfather<div class="parent">father<p>Child elements</p>
        </div>
    </div>
Copy the code

  • In the case of indirect selection, the child element inherits the style of its nearest ancestor element if the attribute is not set. In short, the proximity principle.
  • Of course, if the attribute is set for the child element, then the value of the attribute is adopted, directly selecting > Indirect Inheritance
3. When multiple selectors are used together

Then compare the sum of their weight values and adopt the style of larger weight. The weight values of each selector are as follows:

  • ! The weight of important is infinite (theoretically)
  • Id selector weight: 1000
  • Class selector weight: 100
  • Label selector weight: 10
  • Wildcard weight: 1

The above values are not decimal. For example, the weight of the wildcard “1” is 256

    <style>

       #id {
           background-color: red;
       }

       #id..first {
           background-color: skyblue;
       }
       
    </style>
    <div id="parent" class="first" style="width: 200px; height: 200px;"></div>
Copy the code

Id selector + class selector weight > ID selector, the element is sky blue.

4. In addition, in the case of the same priority, what is written later overwrites the previous style

I believe that after reading the above content, the order of CSS selector priority should be able to master.