C

CSS Handbook

Clean • Professional

CSS Cascade

2 minute

CSS Cascade – Origin, Importance & Order

The CSS Cascade is a fundamental concept that determines which CSS rules are applied when multiple rules target the same element. Understanding the cascade allows developers to write predictable, maintainable styles and avoid conflicts.

The cascade works based on three main factors:

  1. Origin – Where the CSS comes from.
  2. Importance – Whether a rule uses !important.
  3. Order – The sequence in which rules appear in your stylesheet.

Cascade Origins

CSS rules can originate from different sources, each with a different priority. Knowing the origin helps in managing overrides and maintaining consistency.

  • Browser (User Agent) Styles: Default styles applied by browsers, e.g., <h1> tags are bold by default.
  • User Styles: Styles applied by the user via browser settings or custom stylesheets (rarely used).
  • Author Styles: Styles defined by the developer in CSS files, usually taking priority unless overridden by !important.

Example – Author vs Browser:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>CSS Cascade Origins</title>
  <style>
    /* Author style overrides browser default */
    p {
      color: red;   /* Author-defined */
      font-size: 18px; /* Author-defined */
    }
  </style>
</head>
<body>
  <p>This paragraph is styled by the author, overriding browser defaults.</p>
</body>
</html>

Importance (!important)

The !important declaration overrides normal cascade rules, even if a selector has lower specificity. However, overusing it can make your CSS hard to maintain, so it’s recommended to manage specificity properly whenever possible.

Example – Using !important:

<!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 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>

Order of Appearance

When multiple rules have the same origin and specificity, the rule that appears last in the CSS wins. This is known as the source order rule and helps developers layer styles intentionally.

Example – Source Order:

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

    p {
      color: purple; /* This overrides the previous rule */
    }
  </style>
</head>
<body>
  <p>The text is purple because it comes last in the CSS.</p>
</body>
</html>

 

Article 0 of 0