🌿 Inheritance in CSS

πŸ“Œ What Is Inheritance in CSS?

Inheritance in CSS is a mechanism where certain properties are passed down (inherited) from a parent element to its child elements. It helps reduce repetitive code and keeps styles consistent across a page. ✨

>>β€œGood CSS is not written β€” it is inherited.”

🧠 How Inheritance Works

Not all CSS properties are inherited. Some properties naturally pass to children (like color), while others do not (like margin). The browser decides this based on the CSS specification.

πŸ“₯ Inherited Properties

Common properties that *do* inherit include:

  • color 🎨
  • font-family πŸ…΅
  • font-size
  • line-height
  • visibility
  • list-style

β›” Non-Inherited Properties

These properties do NOT inherit by default:

  • margin, padding πŸ“
  • border 🧱
  • width, height
  • background
  • position
  • display

πŸ” Example of Inheritance

Inherited Property Example

body {
  color: blue; /* Children inherit this */
}

p {
  font-size: 20px; /* Only p elements inherit this */
}

In this case, all text inside <body> becomes blue unless overridden.

HTML Structure

<body>
  <div>
    <p>Hello World</p>
  </div>
</body>

πŸ‘‰ The <p> will be blue because the color is inherited from body.

🎯 Controlling Inheritance

CSS provides special keywords that allow you to **override or force inheritance**.

1️⃣ inherit

Forces a property to inherit from the parent.

Using inherit

p {
  border: inherit;
}

2️⃣ initial

Resets the property to its default value.

Using initial

p {
  color: initial;
}

3️⃣ unset

Acts like inherit for inherited properties and initial for non-inherited ones.

Using unset

p {
  font-size: unset;
}

4️⃣ revert

Reverts the property to the value defined by the browser or user-agent stylesheet.

Using revert

p {
  color: revert;
}

Note

πŸ’‘ Tip: Use these keywords when writing reusable components or resetting styles.

🧩 Deep Example: Inheritance in Nested Elements

Nested Example

div {
  color: green;
}

div span {
  font-weight: bold;
}

div span strong {
  color: red; /* Overrides inheritance */
}

HTML

<div>
  Hello <span>beautiful <strong>world</strong></span>!
</div>

βœ”οΈ div sets the base color: green
βœ”οΈ span inherits green
βœ”οΈ strong overrides inherited value β†’ becomes red

πŸ“ Best Practices

  • Use inheritance to reduce repetitive CSS πŸ“‰
  • Set global styles on parent elements (e.g., body)
  • Override only when needed to keep CSS clean ✨
  • Avoid fighting inheritanceβ€”embrace it πŸ§˜β€β™‚οΈ

πŸ”— Helpful Resources

>>β€œWrite CSS that flows naturally. Let inheritance do the heavy lifting.” πŸ’‘