Create your own
Lesson illustration

CSS Specificity and Cascade

Hello! Welcome to your next lesson.

In our last few lessons, we've covered how to apply styles to elements using different selectors, the box model, and background properties. You now have a solid toolkit for styling individual components. However, a common challenge arises when you have multiple, conflicting style rules targeting the same element. For example, what happens if you set a paragraph's color to gray, but a class applied to that same paragraph sets its color to black?

This lesson addresses that exact problem. Our learning outcome is to understand CSS specificity and cascade rules to resolve styling conflicts. We'll demystify the process browsers use to decide which style "wins," a crucial skill for debugging your CSS and writing predictable, maintainable code.

1. The Cascade: How Styles Flow

The "C" in CSS stands for Cascading. This refers to the algorithm the browser uses to resolve conflicts between different style rules. Think of it as a set of tie-breaking rules. The main factors, in order of importance, are:

  1. Origin and Importance: Where the stylesheet comes from and whether a style is marked as !important.
  2. Specificity: How "specific" a selector is.
  3. Source Order: The order in which the rules appear in your code.

Let's start with the broadest concepts: origin and source order.

Origin and Source Order

CSS rules can come from three main origins:

  • User-agent stylesheet: The browser's default styles. This is why an <h1> is large and bold even before you write any CSS.
  • Author stylesheet: The styles you write as the developer. This is where you'll spend all your time.
  • User stylesheet: Custom styles a user might apply in their browser for accessibility or preference.

Generally, your author styles will override the user-agent styles. When two rules from the same origin have the exact same weight, the one that comes last wins. This is the source order rule.

CSS Specificity explained

To see this in action, let's watch a short segment from Kevin Powell's excellent video on specificity. He clearly demonstrates how source order works and how different types of stylesheets (external, internal, and inline) interact.

Watch from the beginning to 02:44. Notice how changing the order of identical selectors affects the final style, and how the browser reads styles from different sources.

Source order is the simplest tie-breaker, but it only applies when the competing rules are otherwise equal. The most common and powerful factor you'll deal with is specificity.

2. Specificity: The Weight of a Selector

When you have multiple rules targeting the same element, the browser doesn't just look at the source order. It first calculates the specificity of each selector to determine which one is more precise. A more specific selector will always beat a less specific one, regardless of source order.

The MDN Web Docs provide the definitive guide on this topic. Please read the following sections to understand how specificity is calculated.

Handling conflicts - Learn web development | MDN

This article, 'Handling conflicts' from MDN Web Docs, is an essential resource. We'll focus on the section that breaks down how specificity is calculated.

Read the section titled 'Specificity' and the sub-section 'Let's now have a look at how the browser calculates specificity.' Focus on the three-column scoring system (IDs, Classes, Elements) and study the table of examples. This mental model is key to understanding the concept.

The Specificity Hierarchy

As you read, you saw that specificity is calculated by counting the number of selectors of each type. You can think of it as a score in three columns: ID - CLASS - ELEMENT.

Selector TypeSpecificity ValueExampleScore
ID1-0-0#main-nav1-0-0
Class, Attribute, Pseudo-class0-1-0.button, [type="submit"], :hover0-1-0
Element, Pseudo-element0-0-1h1, p, ::before0-0-1

Crucially, you compare these scores column by column, from left to right (ID -> Class -> Element). A single ID (1-0-0) is always more specific than any number of classes (e.g., 0-20-0). A single class (0-1-0) is always more specific than any number of elements (e.g., 0-0-20).

Let's see this hierarchy visualized.

CSS Specificity explained

Let's return to Kevin Powell's video. He provides clear visual examples of how this hierarchy works in practice and introduces a helpful calculator tool.

Watch from 02:44 to 08:52. Pay close attention to: How a class selector overrides an element selector (04:35). The demonstration of the specificity calculator and the concept that one column's value is always greater than any value in the columns to its right (05:11). The high specificity of ID selectors and why they should be used with care (07:37).

As a designer, you can think of this like brand guidelines. A rule for a specific component (.profile-card) should naturally override a general rule for all cards (.card), which in turn overrides a base style for all container elements (div).

3. The Exceptions: Inline Styles and !important

There are two ways to override the normal specificity calculation.

  1. Inline Styles: A style applied directly to an HTML element using the style attribute will override any rule in your stylesheets, unless that rule has !important.

    <p style="color: red;">This text will be red.</p>
    

    MDN gives this a conceptual score of 1-0-0-0, placing it in its own, higher-priority column.

  2. The !important Flag: You can add !important to any CSS declaration to make it take precedence over everything else, including inline styles.

    p {
      color: blue !important; /* This will override almost anything */
    }
    

Using !important is often a sign that your CSS has become too complex or "brittle." It breaks the natural cascade and makes your styles hard to debug and predict. It should be avoided whenever possible and is generally considered a last resort.

CSS Specificity explained

Let's see the power—and the danger—of inline styles and !important.

Watch from 08:41 to 11:15. Note how !important creates a new 'specificity war' and why it's problematic for maintaining your code.

4. Best Practices for Healthy Specificity

Your goal should not be to write highly specific selectors, but to write CSS that is predictable and easy to manage. Fighting specificity battles is a frustrating waste of time.

CSS Specificity explained

To conclude, Kevin Powell offers some excellent advice on how to avoid specificity problems in the first place.

Watch from 11:15 to the end. The key takeaway is to rely on classes for styling and avoid overly nested selectors or using IDs for styling.

By giving elements descriptive class names (e.g., .card, .button-primary, .author-bio), you keep specificity low and consistent. This makes your styles modular and reusable, much like creating components in a design system like Figma.

Conclusion

Great job working through this topic! It's one of the trickiest parts of CSS for newcomers, but understanding it is a huge step toward becoming a proficient front-end developer.

Key Takeaways:

  • The browser resolves conflicting styles using the Cascade algorithm.
  • The order of precedence is: Importance (!important) > Inline Styles > Specificity > Source Order.
  • Specificity is a weight calculated for each selector. The hierarchy is ID > Class > Element.
  • A selector's score in a higher-level column (like ID) will always beat any number of selectors in a lower-level column (like Class).
  • To write maintainable CSS, keep specificity low and consistent. Prefer styling with classes over IDs or complex, nested element selectors.

This lesson concludes our module on CSS Fundamentals. You now have a strong foundation in the core principles of styling web pages.

In our next lesson, we'll begin a new module, Responsive Design and Modern CSS. We'll start with one of the most powerful tools for creating layouts: CSS Flexbox. You'll learn how to easily align and distribute items in a container, a fundamental skill for building modern, responsive user interfaces.

Can't find a good explanation? Sign up and we'll make it for you

Sign up