css中:is和:where 伪函数
在 CSS 里,:is() 属于伪类函数,其作用是对一组选择器进行匹配,只要元素与其中任何一个选择器相匹配,就可以应用对应的样式规则。以下是详细介绍:
基本语法
:is() 函数的参数是一个或多个选择器,各个选择器之间用逗号分隔。其基本语法如下:
:is(selector1, selector2, ...) {/* 样式声明 */
}
功能说明
1. 选择器分组
运用 :is() 能够把多个选择器组合起来,让匹配这些选择器的元素应用相同的样式。示例代码如下:
:is(h1, h2, h3) {color: red;
}
2. 简化复杂选择器
在编写复杂选择器时,:is() 能避免重复书写相同的选择器前缀,使代码更简洁。示例如下:
article :is(h1, h2, h3) {font-family: sans-serif;
}
优先级计算
:is() 函数的优先级由其参数中优先级最高的选择器决定。例如:
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>/* 这里 #one-is 的优先级最大, :is(#one-is, .two-is) 的优先级等于#one-is,所以背景都是黄色*/:is(#one-is, .two-is) {background: yellow;}.two-is {background: pink;}</style>
</head><body><div id="one-is">测试is的1</div><div class="two-is">测试is的2</div>
</body></html>
与 :where() 的区别
:is() 和 :where() 都能对选择器进行分组,但二者在优先级计算上有所不同。 :is() 的优先级由其参数中优先级最高的选择器决定,而 :where() 的优先级始终为 0。示例如下:
<!DOCTYPE html>
<html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Document</title><style>/* 这里 #one-is 的优先级最大, :is(#one-is, .two-is) 的优先级等于#one-is,所以背景都是黄色*/:is(#one-is, .two-is) {background: yellow;}.two-is {background: pink;}/* where 的优先级为0, 所以 :where(#one-where, .two-where) 的优先级没有.two-where 的大*//* 测试where的2 的颜色是粉色 */:where(#one-where, .two-where) {background: yellow;}.two-where {background: pink;}</style>
</head><body><div id="one-is">测试is的1</div><div class="two-is">测试is的2</div><div id="one-where">测试where的1</div><div class="two-where">测试where的2</div>
</body></html>
需要注意的是:旧版本浏览器中可能存在兼容性问题,使用时要注意