π 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. β¨
π§ 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
π§© 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 π§ββοΈ