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:
colorfont(includingfont-family,font-size, etc.)visibilitydirection
Example:
body {
color: blue;
}
p {
/* This paragraph will inherit the blue color from the body */
}
3. Properties That Are NOT Inherited
Most **box-related properties** are NOT inherited, such as:
margin,paddingborder,backgroundwidth,heightbox-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 */
}
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) */
}
6. Using unset to Reset Styles
The unset keyword acts as:
inheritfor properties that are normally inherited.initialfor properties that are NOT normally inherited.
p {
color: unset; /* Acts like inherit */
margin: unset; /* Acts like initial */
}
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 */
}
Conclusion
Understanding CSS inheritance helps in writing efficient stylesheets. Use inherit, initial, and unset to control inheritance effectively.