C

CSS Handbook

Clean • Professional

CSS !important Usage and Cascade Layers (@layer)

2 minute

CSS !important Usage and Cascade Layers (@layer)

CSS !important Usage

The !important declaration is a powerful tool in CSS that forces a style to be applied regardless of the usual cascade rules, specificity, or source order. While it can be helpful in some cases, overusing it can make CSS hard to maintain.

What is !important?

Normally, CSS applies styles based on specificity, origin, and order. The !important declaration breaks this hierarchy and ensures the style is applied even if another rule would normally override it.

  • Syntax: property: value !important;
  • Can be applied to any CSS property.

Basic Example

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS !important Example</title>
<style>
  p {
    color: blue; /* Normal rule */
  }

  .highlight {
    color: red !important; /* Overrides all other rules */
  }
</style>
</head>
<body>
  <p class="highlight">This text is red because of !important.</p>
  <p>This text is blue (normal rule).</p>
</body>
</html>

Overriding Inline Styles

Inline styles usually have highest specificity, but !important can even override them.

<p style="color: green;">This text is green (inline style).</p>
<p class="override">This text is red, even overriding inline styles.</p>

<style>
  .override {
    color: red !important;
  }
</style>

When to Use !important

  • Use sparingly to solve specific conflicts.
  • Prefer managing specificity and proper CSS structure over !important.
  • Useful for user stylesheets, third-party overrides, or quick fixes, but not for large-scale styling.

CSS Cascade Layers (@layer)

Cascade layers let you define groups of CSS rules that have their own place in the cascade. Each layer has a priority, and rules in higher layers override rules in lower layers, regardless of order in the stylesheet.

  • Syntax: @layer layerName { ... }
  • Layers can be named or anonymous.
  • You can control layer order using @layer at the top-level.

Basic Example

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS @layer Example</title>
<style>
  /* Define layers */
  @layer reset {
    p {
      color: blue;
    }
  }

  @layer theme {
    p {
      color: green;
    }
  }

  /* Control layer order */
  @layer utilities, reset, theme;
</style>
</head>
<body>
  <p>This paragraph is green because the 'theme' layer overrides 'reset'.</p>
</body>
</html>

Combining Layers with !important and Specificity

  • Styles in a higher layer override lower layers, even if the lower layer has more specific selectors.
  • !important can still override any layer.
@layer base {
  p { color: blue; }
}

@layer components {
  p { color: red !important; } /* Overrides 'base' layer */
}

 

Article 0 of 0