CSS Inheritance

CSS inheritance is a mechanism where child elements inherit certain styles from their parent elements. However, not all properties are inherited by default.

1. What is Inheritance in CSS?

Inheritance allows specific CSS properties (mostly text-related) to be passed down from parent to child elements.

2. Properties That Are Inherited by Default

The following properties are **automatically inherited** by child elements:

  • color
  • font (including font-family, font-size, etc.)
  • visibility
  • direction

Example:

body {
    color: blue;
}

p {
    /* This paragraph will inherit the blue color from the body */
}

Try It Now

3. Properties That Are NOT Inherited

Most **box-related properties** are NOT inherited, such as:

  • margin, padding
  • border, background
  • width, height
  • box-shadow, display

4. Forcing Inheritance Using inherit

You can explicitly apply inheritance to non-inherited properties using inherit.

div {
    background-color: inherit; /* Will take the background color of the parent */
}

Try It Now

5. Overriding Inheritance Using initial

The initial keyword resets a property to its default browser-defined value.

p {
    color: initial; /* Resets color to the browser default (usually black) */
}

Try It Now

6. Using unset to Reset Styles

The unset keyword acts as:

  • inherit for properties that are normally inherited.
  • initial for properties that are NOT normally inherited.
p {
    color: unset; /* Acts like inherit */
    margin: unset; /* Acts like initial */
}

Try It Now

7. Practical Example

body {
    color: green;
}

h1 {
    color: inherit; /* Takes the green color from body */
}

div {
    background-color: inherit; /* Won't work unless the parent has a background color */
}

Try It Now

Conclusion

Understanding CSS inheritance helps in writing efficient stylesheets. Use inherit, initial, and unset to control inheritance effectively.