新增CSS selector(Level4)

173 阅读2分钟

:is()

  1. 作用:简化样式

如果使用过lessscssis上手更快

  1. 用法:is(selector list)
  • 基本用法

image.png A.等价的css写法为:

ol span, 
ul span { 
    color: red; 
}

B.等价的lessscss写法为:

ol, ul {
    span {
        color: red;
    }
}
  • selector list中不合法的selector时,不合法的selector会被忽略,其他selector仍然生效 image.png

  • 优先级为selector list中的最大者

image.png 图中is-pink的优先级为0-1-0,而is伪类的优先级为0-0-2(2个is中均为dom元素)

  1. 浏览器兼容性

image.png

:where()

  1. 作用:简化样式
  2. 用法:where(selector list):is(selector list)一样,二者的区别是where优先级为0

image.png

  1. 流量器兼容性

image.png

:has()

  1. 作用:根据dom层级关系,选中父节点或者前面的兄弟节点
  2. 用法has(selector list)
  • 基本用法

image.png 通过p逆向选中父节点section,并设置了background

  • 多个has串联

image.png 通过2has选中子节点同时有headerfootersection

image.png 特别注意的是,2has之间都不能留白

  • 优先级为selector list中的最大者

image.png 如图所示,根据优先级为参数列表中的最大者的规则,.has-join:has(header):has(footer).has-specific:has(header, main),均有1class2dom元素。前者有2has优先级为0-1-2(1+1,计算了2次),而后者1has优先级为0-1-1

  • 不能嵌套使用has 嵌套使用可能会造成循环
  1. 流量器兼容性

image.png

CSS优先级

ID - CLASS - TYPE

  1. ID: ID选择器
  2. CLASS: class选择器、属性选择器、伪类选择器
  • 属性选择器,如[type="radio"]
  1. TYPE: 类型选择器、伪元素选择器
  • 伪元素: 带有双冒号的选择器,如::before、::placeholder

需要特别注意的是:

  1. 关系选择器: + 、> 、~不会增加权重
  2. :not()、:is()、:has():权重取决于参数列中权重最大的一项
  3. *、:where():权重为0
  4. style attribute指定的内联样式,具有高于ID的优先级
  5. important具有最高优先级

参考资料:

  1. :is()
  2. :whiere()
  3. :has()
  4. selector 优先级