Skip to content

CSS !重要不 工作

快速摘要

你的 !重要规则是 不 winning 因为 another 规则使用 !重要有 higher specificity, or 规则是 不 matching.

为什么发生

  • Another !重要规则使用 higher specificity 是 overriding 它

  • CSS selector 是不 matching 目标元素

  • Inline 样式使用 !重要 override stylesheet 规则

最小示例

✗ 错误代码
/* Specificity: 0-1-0 */
.btn { color: red !important; }
/* Specificity: 1-0-0 — wins even with !important on both */
#special-btn { color: blue !important; }
✓ 修复代码
/* Increase specificity to match or exceed */
#special-btn.btn { color: red !important; }

当两者都规则有 !重要, specificity decides. #特殊-btn (1-0-0) beats .btn (0-1-0). Increase 你的 selector's specificity 到 win.

如何诊断

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

  • 检查如果 another !重要规则使用 higher specificity exists

  • 验证 selector matches 元素

如何修复

  • Increase specificity 的你的 !重要规则

  • 移除 competing !重要 declaration

  • Use inline 样式使用 !重要 as 最后 resort

如何预防

  • Avoid !重要 — use specificity and 源顺序相反

  • Use structured CSS 架构 (BEM, CSS 模块) 到 avoid conflicts

相关资源

相关术语

相关课程

← 返回语言