Rules about CSS selector priority

Simple rules:

!important > inline styles > id selectors > class selectors > element selectors > wildcard selectors

Examples of selectors:

!important:

<h1 id="title">好好学习,天天向上</h1>
<style type="text/css">
    #title {
        color:red !important;
    }
</style>
  • Different selectors pointing to the same element, the one with higher weight value (described below) !important has higher priority
  • The weight value is the same, and the !important with the lower position has higher priority (the latter comes first)

Inline styles:

<h1 style="color:red">好好学习,天天向上</h1>

id selector

<h1 id="title">好好学习,天天向上</h1>
<style type="text/css">
    #title {
        color:red;
    }
</style>

class selector:

<h1 class="title">好好学习,天天向上</h1>
<style type="text/css">
    .title {
        color:red;
    }
</style>

Element selector:

<h1>好好学习,天天向上</h1>
<style type="text/css">
    h1 {
        color:red;
    }
</style>

Universal selector:

<h1>好好学习,天天向上</h1>
<style type="text/css">
    * {
        color:red;
    }
</style>

Detailed rules:

Each selector has a weight value in the format (a,b,c)

a means: the number of [id] selectors in a selector

b means: the number of [classes, pseudo-classes, attributes] selectors in a selector

c means: the number of [element, pseudo-element] selectors in a selector 

Compare digit by digit from the first digit, the priority of the larger number is higher, if the same compare the next digit

The universal selector weight is (0, 0, 0)

Note: In vscode, move the mouse over the selector to display the structure and weight value

Click Selector Specificity to open the official document 

This document has a detailed description of weight calculation and other related knowledge 

 Document address: https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity

If the weight values ​​are the same, the latecomer will come first, and the one with the lower position will have higher priority

 

 

Guess you like

Origin blog.csdn.net/m0_53206841/article/details/128442112