Skip to content

noImportantStyles

¥Summary

¥How to configure

biome.json
{
"linter": {
"rules": {
"complexity": {
"noImportantStyles": "error"
}
}
}
}

¥Description

禁止使用 !important 样式。

¥Disallow the use of the !important style.

!important CSS 样式是一种声明,用于赋予特定规则高于其他冲突规则的优先级。当应用于 CSS 属性时,该属性的值将优先于任何其他声明,无论其在样式表中的优先级或出现顺序如何。

¥The !important CSS style is a declaration used to give a specific rule higher precedence over other conflicting rules. When it is applied to a CSS property, that property’s value is prioritized over any other declarations, regardless of specificity or order of appearance in the stylesheet.

¥How !important Works

  • 通常,CSS 规则遵循层叠顺序,浏览器会根据优先级、继承性和与目标元素的接近程度来决定应用哪些规则。

    ¥Normally, CSS rules follow a cascade order, where the browser decides which rules apply based on specificity, inheritance, and proximity to the targeted element.

  • 在规则中添加 !important 会覆盖此级联逻辑,强制该规则生效,即使其他规则具有更高的优先级或定义时间更晚。

    ¥Adding !important to a rule overrides this cascade logic, forcing the rule to apply even if other rules have higher specificity or are defined later.

¥Why !important Should Be Avoided

虽然 !important 可以解决特定的、即时的样式问题,但它的影响可能会导致代码库中出现长期问题:

¥While !important can solve specific and immediate styling issues, its effects can result in long-term problems within a codebase:

  • 打破级联逻辑:会覆盖级联规则的自然流程,使得预测哪些样式会应用变得更加困难。

    ¥Breaks the Cascade Logic: It overrides the natural flow of cascading rules, making it harder to predict which styles will apply.

  • 增加了复杂性:一旦样式表中使用了 !important,其他开发者可能会更频繁地使用它,从而形成覆盖循环,增加维护难度。

    ¥Increases Complexity: Once !important is used in a stylesheet, other developers may respond by using it even more aggressively, creating a cycle of overrides and increasing maintenance difficulty.

  • 降低可重用性:覆盖样式通常会降低组件的灵活性,因为未来的调整需要更多的工作。

    ¥Reduces Reusability: Overriding styles often makes components less flexible, as future adjustments require more effort.

  • 妨碍调试:调试风格变得更加复杂,因为开发者必须考虑 !important 规则覆盖预期行为的情况。

    ¥Hinders Debugging: Debugging styles becomes more challenging, as developers must account for the !important rule overriding expected behavior.

¥Examples

¥Invalid

.style {
color: red !important;
}
code-block.css:2:16 lint/complexity/noImportantStyles  FIXABLE  ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Avoid the use of the !important style.

1 │ .style {
> 2 │ color: red !important;
^^^^^^^^^^
3 │ }
4 │

This style reverses the cascade logic, and precedence is reversed. This could lead to having styles with higher specificity being overridden by styles with lower specificity.

Unsafe fix: Remove the style.

2 │ ····color:·red·!important;
-----------

¥Useful links

¥Related links