Inheritance

HTML pages are actually document trees, with ancestors, descendants, parents and children - just like a human family tree.

In a human family, certain traits are passed down from ancestors to descendants. In a document tree, some CSS properties are passed down from ancestor elements to descendant elements. This is called inheritance.

Inheritance is designed to save you having to specify CSS rules for each level of element in the document tree.

For example, if you specify a color for the <body>, this color will be inherited by all other elements on the page, unless they have their own specific styles.

body { color: blue; }

Document tree diagram showing universal selectors

There are certain properties that are not inherited, including margins, padding, borders and backgrounds. There is a very good reason for this. If all CSS properties were to be inherited, we would have to "turn them off" at every level below if they were not required.

For a full list of all CSS2 properties and their inheritance, see the W3C Property index.

Font-size and inheritance

The font-size property is not directly inherited like other properties. Rather than the entire declaration being inherited, only the calculated value is inherited. This is not obvious when you set an absolute value like 14px, but becomes very obvious when you use relative values such as 80% or .8em. Relative values are calculated before being passed on to the child element only.

For example, if you set a relative font-size on a <div> element, this will only be passed down to the children, not all descendants. So, the <em> and <p> elements directly under the <div> will inherit the calculated size, but the descendants, such as the <strong> element, will not.

div { font-size: 85%; }

Diagram of inherited font-size

Font-size calculation can sometimes have some strange side-effects. For example, if you apply relative font-size of 80% to a <div> element, other nested <div> elements will also inherit the size - which means that they will have a font size of 80% x 80% = 64%.

The solution is to either apply relative font sizing at one level only, or to target specific instances of an element. Instead of using an overall type selector, you could use combined type and ID selectors:

div#main { font-size: 85%; }

Further information

Cascade »

Other Max Design articles and presentations
Associated with webstandardsgroup.org