内联样式(style属性)优先级最高,权值为1000,强制覆盖外部CSS中带!important的规则;唯一能覆盖它的!important必须写在style属性内,如style="color:red!important"。

内联样式优先级高于带 !important 的普通 CSS 规则,但 !important 可以压过内联样式——前提是它也出现在内联样式里。
内联样式为什么总赢过外部 CSS 里的 !important
浏览器计算优先级时,先按「来源类型」分档:style 属性属于最高档位(作者样式中的“内联”子档),而 <style></style> 或 .css 文件属于低一档的“作者样式(非内联)”。!important 只能翻倍它自己所在档位的权重,无法越级覆盖更高来源的声明。
常见错误现象:div { color: red !important; } 完全无效,如果目标元素是 <div style="color: blue;">。
<ul>
<li>内联样式的权重是 <code>(1, 0, 0, 0),不依赖选择器,天生满格
!important 在外部 CSS 中只是把原本的 (0, 0, 1, 0) 拉到 (0, 0, 1, 0) + important,仍卡在非内联档位!important,必须写在 style 属性里,比如 style="color: red !important;"
怎么判断当前颜色到底被谁控制?
别猜,直接看 Chrome DevTools 的 Elements 面板:被划掉的属性说明被更高优先级覆盖;没划掉但没生效,大概率是 JS 动态写了 element.style.color = "xxx"。
立即学习“前端免费学习笔记(深入)”;
- 检查
Computed标签页里的color值,点开右侧小箭头,能看到所有参与计算的来源及是否被覆盖 - 注意区分「继承来的 color」——它权重为 0,任意显式声明都能盖掉,哪怕只是
p { color: inherit; } - 如果看到
是空的,但元素仍有内联色,说明 JS 清过element.style.cssText后又重设了某几项
!important 在内联样式中怎么写才有效?
语法上允许,但极少用。它只对内联样式自身起作用,且仅当存在多个内联声明冲突时才有意义(比如 JS 多次赋值)。
- 合法写法:
<p style="color: red !important; font-size: 14px;"></p> - 无效写法:
<p style="color: red;"></p>+ 外部p { color: blue !important; }→ 蓝色不会生效 - 更现实的场景:某些 UI 库或编辑器会输出带
!important的内联样式,此时想覆盖它,只能靠更高来源(如浏览器扩展注入的 CSS)或直接操作element.style对象
真正难缠的不是 !important 本身,而是它常掩盖了 JS 直接改 style 属性这个事实——查不到规则,就去查运行时的 element.style 对象。


















