CSS Inheritance
When an element has no value specified for a property, inheritance decides what happens. The property either takes its value from the parent element or falls back to its initial (default) value.
Which of the two applies depends on the type of property:
- inherited properties
- non-inherited properties
Inherited Properties
By default, an inherited property with no value of its own receives the computed value of the parent element.
Text-related properties usually work this way, color, font-family, font-size, line-height and text-align among them, which keeps text styling consistent across a document.
Below, the parent <p> element passes its color and font-size values down to the <strong> element, so the text inside it is blue and 20px.
Example
Both color and font-size pass down from the paragraph here:
Output: complete HTML page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Inherited Properties</title>
<style>
p {
color: blue;
font-size: 20px;
}
</style>
</head>
<body>
<p>This is a paragraph with some <strong>important</strong> text.</p>
</body>
</html>
Non-inherited Properties
Without a set value, a non-inherited property simply uses its own initial (default) value.
Box model and layout properties usually behave this way, including border, background, margin, padding, width and height.
Below, border-style starts out as none, so the <strong> element gets no additional border, even though the <p> element around it has one.
Example
border stays on the paragraph and does not pass down here:
Output: complete HTML page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Non-inherited Properties</title>
<style>
p {
border: 1px solid red;
}
</style>
</head>
<body>
<p>This is a paragraph with some <strong>important</strong> text.</p>
</body>
</html>
The inherit Keyword
To request inheritance explicitly, write the inherit keyword, which works on inherited and non-inherited properties alike.
Below, it tells the <strong> element inside the <p> element to take the border value of its parent, so the <strong> element gets an additional border.
Example
Here the inherit keyword asks for the inheritance explicitly:
Output: complete HTML page
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS inherit Keyword</title>
<style>
p {
border: 1px solid red;
}
strong {
border: inherit;
}
</style>
</head>
<body>
<p>This is a paragraph with some <strong>strong</strong> text.</p>
</body>
</html>