tezvyn:

CSS Cascade: How Browsers Resolve Style Conflicts

AI-drafted, machine-checkedSource: w3.orgbeginner

The CSS Cascade is a tie-breaking algorithm that decides which style rule applies when multiple rules target the same element. It resolves conflicts between browser defaults, user styles, and your CSS.

WHY IT EXISTS: Web pages need a predictable way to resolve style conflicts. Without a cascade, how would a browser decide which color to apply if a paragraph is styled by a browser default, a user's custom stylesheet, and the website's own CSS? The cascade provides a clear, multi-step algorithm to pick one winner.

THE MENTAL MODEL: Think of the cascade as a judge settling a dispute over an element's style. The judge first considers the rule's origin (browser, user, or author). Then, it weighs its importance (!important). After that, it examines the specificity of the selector (an ID is stronger than a class). Finally, if it's still a tie, the judge rules in favor of the last one defined in the code.

HOW IT WORKS: The cascade sorts all declarations for a property on an element to find the single winning value. The sorting follows a strict order of precedence. First, it considers origin and importance. The browser sorts rules based on their source and whether they have !important. Author !important rules (your code) beat normal author rules. Second, if origin and importance are equal, it compares specificity. A more specific selector, like #main .article p, beats a general one like p. Third, if all else is equal, source order is the tie-breaker: the rule that appears later in the stylesheet wins.

WHEN TO USE IT: You are always using the cascade, whether you realize it or not. Understanding it is key to writing efficient, maintainable CSS. You consciously leverage it when you write a more specific selector to override a general style from a library, or when you place a reset stylesheet before your component styles.

WHEN NOT TO USE IT: You don't "turn off" the cascade, but you can fight against it, which is an anti-pattern. The primary mistake is littering code with !important to solve specificity problems. This is a short-term fix that creates long-term debt by making styles rigid and hard to override later. A better approach is to refactor your selectors to have appropriate specificity.

ONE CANONICAL EXAMPLE: Imagine this HTML: Hello and this CSS: #intro { color: blue; } p.main { color: red; } p { color: green; } The paragraph text will be blue. Even though the red rule is defined after the blue rule, the ID selector (#intro) has higher specificity than the class selector (p.main), so it wins the cascade. The green rule has the lowest specificity and is overridden by both.

Read the original → w3.org

Get five bites like this every day.

Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.