CSS Inheritance
Inheritance is the passing of a property value from a parent element down to its children. Some properties pass down and most properties do not.
Colour passes down
The body rule sets one colour for the page. Each list item sits deep inside the body, and it computes that same colour.
body {
color: blue;
}A border stays put
The box rule draws a border on the box. The heading inside the box gets no border, because border does not pass down.
.box {
border: 2px solid red;
}An own rule beats inheritance
The box sets red for its children. The paragraph inside has its own rule, so it turns blue while the heading stays red.
.box {
color: red;
}
.box p {
color: blue;
}Example
body {
color: blue;
}
.box {
border: 2px solid red;
color: green;
}
.box p {
color: orange;
}Key points
- Inheritance: the passing of a value from a parent element to its children
- color, font-family and text-align pass down to children.
- margin, border and background do not pass down to children.
- A value set directly on an element beats an inherited value.
- The inherit keyword forces a property to take the value of its parent.
- Inheritance is why a colour set on body can style a whole page.
In this example, the body rule sets blue for the whole page. A list item inherits that blue through its parent list. The box rule sets green, so the heading inside inherits green. The paragraph inside the box has its own orange rule, and that direct rule wins. The border on the box does not pass to the heading at all.
Try it Yourself
Edit the code, then press Run.
Runs in your browser โ the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
A rule sets color on a parent element and no rule sets color on its child. What colour does the child use?