CSS 选择器优先级
当多个选择器作用于同一元素时,优先级决定哪个样式生效。
优先级计算规则
优先级用 (A, B, C, D) 四元组表示:
| 选择器类型 | 权重 | 示例 |
|---|---|---|
| !important | 最高(内联) | color: red !important; |
| 内联样式 | (1, 0, 0, 0) | style="color: red" |
| ID 选择器 | (0, 1, 0, 0) | #header |
| 类/伪类/属性选择器 | (0, 0, 1, 0) | .btn、:hover、[type] |
| 元素/伪元素选择器 | (0, 0, 0, 1) | div、::before |
| 通配符/组合符 | (0, 0, 0, 0) | *、>、+、~ |
计算示例
CSS
/* (0, 1, 0, 0) = 100 */
#header { color: blue; }
/* (0, 0, 2, 1) = 21 */
.nav .link span { color: green; }
/* (0, 0, 1, 2) = 12 */
div p a { color: red; }
/* (0, 0, 2, 0) = 20 */
.nav.link { color: yellow; }
/* 优先级: #header > .nav .link span > .nav.link > div p a */
从左到右逐位比较,不进位:
CSS
(0, 1, 0, 0) > (0, 0, 99, 99) /* ID 胜过任意数量类 */
特殊情况
!important 覆盖一切
HTML
.text { color: red !important; } /* 优先级最高 */
#header .text { color: blue; } /* 被 !important 覆盖 */
谨慎使用 !important,仅用于覆盖第三方样式。
内联样式优先级最高
CSS
<div style="color: red;"> <!-- 内联样式优先级高 -->
<style>
#text { color: blue; } /* 被 style 属性覆盖 */
</style>
</div>
相同优先级后者生效
CSS
.text { color: red; }
.text { color: blue; } /* 生效 */
层叠上下文
CSS
/* 来源优先级(从高到低)*/
1. 用户代理 !important
2. 用户 !important
3. 作者 !important
4. 作者普通样式
5. 用户普通样式
6. 用户代理普通样式
实用技巧
提升优先级
CSS
/* 方式一:增加类选择器 */
.btn.btn { } /* (0, 0, 2, 0) */
/* 方式二:使用 :where() 降低优先级 */
:where(.btn) { } /* 优先级为 0 */
/* 方式三:使用 ID 选择器 */
#container .btn { } /* (0, 1, 1, 0) */
CSS Modules 避免冲突
CSS
/* 生成唯一类名,避免全局冲突 */
.btn_component__active__x7j3s { }
BEM 命名规范
CSS
/* Block__Element--Modifier */
.card { }
.card__header { }
.card__title--primary { }
常见陷阱
CSS
/* 陷阱:误以为层级深优先级高 */
.header .nav .menu .item a { } /* (0, 0, 3, 1) */
/* 实际:单个 ID 更高 */
#link { } /* (0, 1, 0, 0) 胜出 */
text
/* 陷阱:伪类权重低 */
a:hover { } /* (0, 0, 1, 1) */
a:visited { } /* (0, 0, 1, 1) 相同,后者生效 */
要点总结
- 优先级计算:(ID, 类, 元素),从左到右比较
- !important 优先级最高,但应少用
- 内联样式优先级仅次于 !important
- 相同优先级时,后者覆盖前者
- 使用 BEM 或 CSS Modules 避免命名冲突
- 避免过度嵌套,保持选择器简洁
📝 发现内容有误?点击此处直接编辑