CSS: Concept: !important

20th August 2020 at 2:19pm

大部分情况下你都不应该用 !important。这会让你的样式混乱且难调试。MDN 总结出了这些规则:

  • Always look for a way to use specificity before even considering !important
  • Only use !important on page-specific CSS that overrides foreign CSS (from external libraries, like Bootstrap or normalize.css).
  • Never use !important when you're writing a plugin/mashup.
  • Never use !important on site-wide CSS.

!important 的 declaration 的 specificity 会高于不带的。如果多个 !important 属性冲突,会优先使用 specificity 高的;如果 specificity 一致,会优先选择后声明的。