CSS 选择器的优先级

选择器优先级排序

简短而言,选择器的优先级可以按照如下方式排序:
内联 > ID 选择器 > 伪类 = 属性选择器 = 类选择器 > 元素选择器[p] > 通用选择器(*) > 继承样式

BUT,CSS 选择器究竟是如何计算优先级的?

优先级计算规则

例如,有如下选择器:

1
2
3
#nav ul li a.myclassname:hover {
color: blue;
}

其优先级计算结果为:

  • Inline
    0
  • IDs
    1
  • Classes
    2
    & pseudo class
    & attributes
  • Elements
    3
    & pseudo Elements

再如:

1
* {}
  • Inline
    0
  • IDs
    0
  • Classes
    0
    & pseudo class
    & attributes
  • Elements
    0
    & pseudo Elements

再再如:

1
2
3
4
5
6
.blue {
color: blue;
}
p span span span span span span span span span {
color: red;
}
  • Inline
    0
  • IDs
    0
  • Classes
    1
    & pseudo class
    & attributes
  • Elements
    0
    & pseudo Elements
  • Inline
    0
  • IDs
    0
  • Classes
    0
    & pseudo class
    & attributes
  • Elements
    10
    & pseudo Elements

上面谁的优先级更高???(经测试此处与 CSS 的顺序无关)

另外,优先级相同的情况下,class 在 HTML 中的书写顺序并不会影响样式呈现。

如果加了 !important 呢?

1
2
3
#nav .nav .item p span {
color: blue !important;
}
  • 0
  • 1
  • 2
  • 2
  • 0
  • 0
  • 0
  • 0

样式优先级如下:


!important
  • IDs
  • Classes
  • Elements


Inline
  • Inline


Normal
  • IDs
  • Classes
  • Elements


关于性能:CSS 选择器总是从右向左匹配;最右边的选择器匹配到的元素越少越好。