2 min read

CSS Cascade and Inheritance

The "C" in CSS stands for Cascading. Understanding the cascade and inheritance is fundamental to understanding how styles are applied to elements.

1. The Cascade

The cascade is the algorithm that browsers use to resolve conflicts when multiple rules apply to the same element. It determines which property value wins.

The cascade considers three main factors, in order of importance:

  1. Importance: !important vs. normal declarations.
  2. Specificity: The weight of the selector (ID > Class > Tag).
  3. Source Order: The order in which rules appear in the stylesheet.

Source Order

If two rules have the same importance and specificity, the one that appears last in the CSS wins.

p {
  color: red;
}

p {
  color: blue; /* This wins because it comes later */
}

2. Inheritance

Inheritance is the mechanism by which some properties pass down from a parent element to its children.

Inherited Properties

Some properties are inherited by default. These are typically text-related properties.

  • color
  • font-family
  • font-size
  • font-weight
  • line-height
  • text-align
  • visibility
body {
  color: green;
}

p {
  /* The paragraph inherits the green color from the body */
}

Non-Inherited Properties

Most box-model and layout properties are not inherited by default.

  • width, height
  • margin, padding, border
  • background
  • position, display

3. Controlling Inheritance

You can force inheritance or reset properties using special keywords.

  • inherit: Forces a property to inherit the value from its parent, even if it normally wouldn't.
    button {
      font-family: inherit; /* Inherit font styles from parent */
    }
  • initial: Sets the property to its default value defined in the CSS specification.
    • Note: This is not the browser default. For example, the initial value of display is inline. So div { display: initial; } makes the div inline, not block.
  • unset: Acts as inherit if the property is naturally inherited, and initial if it is not.
  • revert: Resets the property to the browser's default stylesheet (user agent styles). This is usually what you want when you want to "reset" an element to its standard browser appearance.

Example: initial vs revert

div {
  /* Sets display to 'inline' (CSS spec default) */
  display: initial; 
}

div {
  /* Sets display to 'block' (Browser default for div) */
  display: revert; 
}

programming/css/css programming/css/specificity programming/css/css-layers