CSS Inheritance and Grouping

CSS Inheritance and Grouping

Inheritance is an efficiency feature of CSS. It means you have to write far less code. An HTML page is organized into parents and children. A child element of a parent element is any element that's enclosed by the parent element.

In an HTML document, the parent of all the content that displays on the page is <body>. Everything on the page is a child of <body>, because every element is enclosed by the <body> tags. For example,

<p>Hello, World</p>

The paragraph is enclosed by the opening and closing <body> tags, so it is children of <body>. As the body element's children, it inherits all the CSS properties of that element. For example,

body {
font-family: Georgia, “Times New Roman”, Times, serif;
font-size: 1.2em;

All the text on the page will display in Georgia or one of the alternatives, at 1.2 times the default size. You can also override the inheritance.

p {
font-family: “Trebuchet MS”, Helvetica, sans-serif;
font-size: .5em;

When you override an inherited size with an em value, the new em value is relative to the inherited size. The style that the p element inherits from the body element is 1.2em. So when you style the p element at .5em, you are saying, "Make p elements half the inherited size." The inherited size, style of the body element, is 1.2 times the default size. So, half of that size, specified by .5em, is .6 times the default size.


You can group elements that share one or more style characteristics. For example, if h1, h2, and h3 headings are all to be in the Arial font or one of its relatives and centered, you can write

h1, h2, h3 {
font-family: Arial, Helvetica, sans-serif;
text-align: center;

All three types of headings share the same font-family and text alignment. You can also individually style these elements with other characteristics.