Inheritance
Inheritance is when child elements inherit CSS property values from their parents. Properties like color, font, and line-height inherit; layout properties like margin and padding do not. Understanding which properties inherit is crucial.
Inherited Properties
Category | Properties | Inherited? |
|---|---|---|
Text | color, font-family, font-size, line-height | Yes |
Layout | margin, padding, border, width, height | No |
Display | display, position, float | No |
Visibility | opacity, visibility | No |
CSS
/* Inherited properties */
body {
color: black;
font-family: Arial;
font-size: 16px;
}
/* Children inherit these */
p {
/* Inherits color: black */
/* Inherits font-family: Arial */
/* Inherits font-size: 16px */
}
/* Non-inherited properties */
.parent {
margin: 20px;
padding: 10px;
}
.child {
/* Does NOT inherit margin */
/* Does NOT inherit padding */
}Controlling Inheritance
CSS
/* Force inheritance with inherit */
.child {
width: inherit;
/* Child gets parent's width */
margin: inherit;
/* Child gets parent's margin */
}
/* Reset to default with initial */
.element {
color: initial;
/* Resets to browser default */
}
/* Revert to inherited value */
.element {
color: revert;
/* Uses browser's default or inherited */
}
/* Unset (removes all declarations) */
.element {
all: unset;
/* Removes all CSS from this element */
}Note
Typography properties inherit (color, font). Layout properties don't (margin, padding). Use inherit, initial, revert to control inheritance behavior.
Next
Important: [!important](/css/important).