css选择器优先级

之前理解的css选择器优先级是这样的
!important >内联样式> id > class > 元素选择器 > 伪元素

看了一下w3c的文档规范,发现压根没有我想的这么简单

!important > 内联样式 没有变化

先说说有哪些选择器:

  1. 类型选择器(type selectors)(例如, h1)
  2. 伪元素(pseudo-elements)(例如, ::before)
  3. 类选择器(class selectors) (例如,.example)
  4. 属性选择器(attributes selectors)(例如, [type="radio"]),
  5. 伪类(pseudo-classes)(例如, :hover)
  6. ID选择器(例如, #example)
  7. 通用选择器(universal selector)(*)
  8. 组合子(combinators) (+, >, ~, ' ')
  9. 否定伪类(negation pseudo-class)(属于伪元素)(:not)

这些元素的特异性如下

  • ID选择器的个数(=a)
  • 类选择器、属性选择器、伪类的个数(=b)
  • 类型选择器、属性选择器、伪元素的个数(=c)

连接abc为一个三位数,计算他们的优先级:

*               /* a=0 b=0 c=0 -> 优先级 =   0 */
LI              /* a=0 b=0 c=1 -> 优先级 =   1 */
UL LI           /* a=0 b=0 c=2 -> 优先级 =   2 */
UL OL+LI        /* a=0 b=0 c=3 -> 优先级 =   3 */
H1 + *[REL=up]  /* a=0 b=1 c=1 -> 优先级 =  11 */
UL OL LI.red    /* a=0 b=1 c=3 -> 优先级 =  13 */
LI.red.level    /* a=0 b=2 c=1 -> 优先级 =  21 */
#x34y           /* a=1 b=0 c=0 -> 优先级 = 100 */
#s12:not(FOO)   /* a=1 b=0 c=1 -> 优先级 = 101 */

参考链接:
css3选择器w3c标准
css2选择器w3c标准
MDN

原文地址:https://www.cnblogs.com/emilyzhou/p/13386251.html