跳到主要内容

优先级

优先度计分

每一个选择器规则会有一个分数,有最高分数的选择器将会被应用。

在一个真实的项目中应当确保你期望的 CSS 都会被实际应用到,来降低优先度分数,避免复杂度上升。

计分方式

  1. * 通用选择器没有优先度,0分

  2. 元素(类型)或伪元素选择器 ,1 分

  3. 类、伪类或属性选择器,10 分

    :not() 不会参与计分,但是参数会计分:

    /* `div` 和 `.my-class` 一共 11 分 */
    div:not(.my-class) {
    color: red;
    }
  4. ID 选择器,100 分

  5. 内联样式属性,1000 分

  6. !important,10000 分

    /* 一共 10000 分 */
    .my-class {
    color: red !important; /* 10000 分 */
    background: white; /* 10 分 */
    }

​一个优先度计算例子:

​a.my-class.another-class[href]:hover {
color: lightgrey;
}

一共41分:

  • a 得 1 分

  • .my-class 得 10 分

  • .another-class 得 10 分

  • [href] 得 10 分

  • :hover 得 10 分

有相同优先级分数的会使用最新(后)的选择器。

必要的时候可以通过重复写选择器来获得较高优先级,但不要随意使用:

/* 该优先级会比后者高 */
.my-button.my-button {
background: blue;
}

button[onclick] {
background: grey;
}

可以在 Specificity Calculator 模拟计算一个选择器的优先级。

可视优先级

可以以这样的格式表示一个选择器的优先级:

[ID 数] - [类、属性、伪类数] - [元素、伪元素数]

比如这个例子得可视优先级为 "0-4-1" :

a.my-class.another-class[href]:hover {
color: lightgrey;
}

可以参考这些网站:


参考

Specificity,Learn CSS - web.dev

优先级 - MDN

Specificity Calculator - keegan.st

CSS Specifishity - specifishity

Specifics on CSS Specificity, Chris Coyier - css-tricks

CSS Specificity Calculator - polypane.app