🔖 webfrontendcss

选择器优先级

  • CSS 选择器类型的优先级: 内联样式 > ID 选择器 > 类选择器 > 标签选择器

    具体计算规则如下,其中 (a,b,c,d) 将作为向量比较大小,即左侧的数值有绝对优先权

    A specificity is determined by plugging numbers into (a,b,c,d):

    • If the styles are applied via the style attribute, a=1; otherwise, a=0.
    • b is equal to the number of ID selectors present.
    • c is equal to the number of class selectors, attribute selectors, and pseudo classes present.
    • d is equal to the number of type selectors and pseudo elements present.
  • 以下选择符对优先级没有影响

    • 通配选择符 (universal selector): *
    • 关系选择符 (combinators): +, >, ~, , ||
    • 否定伪类 (negation pseudo-class): :not() 但是在 not() 内部声明的选择器会影响优先级
  • 栗子

    SelectorSpecificity
    div(0,0,0,1)
    div span(0,0,0,2)
    div > span ~ i(0,0,0,3)
    div button[type="button"](0,0,1,1)
    div.container(0,0,1,1)
    div .container.container(0,0,2,1)
    .container.container(0,0,2,0)
    .container.container div(0,0,2,1)
    .container .container div(0,0,2,1)
    #container(0,1,0,0)
    #container a:hover(0,1,1,1)

特殊规则

  • !important: 此声明将覆盖任何其它声明

  • 内联样式中使用 !important 无法被覆盖

  • 属性直接的约束可能越过优先级规则,比如 max-width 强于 width,因此下面的样式中即便声明了 width: 500px !important;(React 的 style 属性不支持 important 声明),最终的效果也只是 200px,因为 max-width 拥有更强的约束:

    width: 200px

    height: 200px

    类似的,widthmin-width, heightmax-height, heightmin-height 也满足此类约束。

© 2017-2025 光和尘有花满渚、有酒盈瓯

Comments