Skip to content

CSS Specificity War

快速摘要

你的 CSS 规则是 是 overridden 通过更多特定规则, and 你 cannot figure out 为什么的样式是 不 applying.

为什么发生

  • ID selector (1-0-0) overrides 你的类 selector (0-1-0)

  • Inline 样式 override 你的 stylesheet 规则

  • 框架 or 库 uses highly 特定 selectors

  • Nested selectors 创建 unintended 高 specificity

最小示例

✗ 错误代码
/* Framework: specificity 1-0-0 */
#header { color: black; }
/* Your rule: specificity 0-1-0 — loses */
.header-text { color: blue; }
✓ 修复代码
/* Match specificity: 1-1-0 */
#header .header-text { color: blue; }
/* Or better: remove the ID selector */
.header { color: blue; } /* If you control the HTML */

ID selector (1-0-0) beats 类 selector (0-1-0). 要么 increase 你的 specificity or, better, replace ID 使用类.

如何诊断

  • Inspect 元素 in DevTools — look for struck-通过规则

  • 检查 specificity 的 competing 规则

  • Look for inline 样式 on 元素

如何修复

  • Increase specificity 的你的 selector 到 match or exceed competing 规则

  • 移除不必要 ID selectors in favor 的类

  • Use CSS methodology 如 BEM 到 keep specificity 低 and consistent

如何预防

  • Use BEM or another CSS methodology 到 avoid specificity issues

  • Prefer 类 over IDs for 样式

  • Avoid inline 样式 except for 动态值 从 JavaScript

相关资源

相关术语

相关课程

← 返回语言