关于CSS选择器优先级的规则说明

简单规则:

!important > 行内样式 > id选择器 > 类选择器 > 元素选择器 > 通配选择器

选择器举例说明:

!important:

<h1 id="title">好好学习,天天向上</h1>
<style type="text/css">
    #title {
        color:red !important;
    }
</style>
  • 指向同一元素的不同选择器,权重值(下文中有介绍)高的 !important 优先级更高
  • 权重值相同,位置靠后的 !important 优先级更高 (后来者居上)

行内样式:

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

id选择器

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

类选择器:

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

元素选择器:

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

统配选择器:

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

详细规则:

每个选择器都有一个权重值,格式为(a,b,c)

a表示:一个选择器中【id】选择器的个数

b表示:一个选择器中【类、伪类、属性】选择器的个数

c表示:一个选择器中【元素、伪元素】选择器的个数 

从第一位开始逐位对比,数字大的优先级高,如果相同对比下一位

统配选择器权重为(0,0,0)

注:在vscode中,将鼠标移至选择器上,可显示结构和权重值

点击Selector Specificity可打开官方文档 

此文档有权重值计算及其他相关知识的详细说明 

 文档地址:https://developer.mozilla.org/en-US/docs/Web/CSS/Specificity

如果权重值相同,则后来者居上,位置靠后的优先级更高

猜你喜欢

转载自blog.csdn.net/m0_53206841/article/details/128442112