Pages

Labels

Powered by Blogger.
Wednesday, September 5, 2012

Inheritance


People often confuse inheritance with the cascade. Although they seem related at first glance, the two concepts are actually quite different. Luckily, inheritance is a much easier concept to grasp. Certain properties, such as color or font size, are inherited by the descendants of the elements those styles are applied to. For instance, if you were to give the body element a text color of black, all the descendants of the body element would also have black text. The same would be true of font sizes. If you gave the body a font size of 1.4 ems, everything on the page should inherit that font size. I say  should because IE for Windows and Netscape have problems inheriting font sizes in tables. To get around this, you will either have to specify that tables should inherit font sizes or set the font size on tables separately.



If you set the font size on the body, you will notice that this style is not picked up by any headings on the page. You may assume that headings do not inherit text size. But it is actually the browser default style sheet setting the heading size. Any style applied directly to an element will always override an inherited style. This is because inherited styles have a null specificity.

Inheritance is very useful, as it lets you avoid having to add the same style to every descendant of an element. If the property you are trying to set is an inherited property, you may as well apply it to the parent element. After all, what is the point of writing this:

p, div, h1, h2, h3, ul, ol, dl, li {color: black;}

when you can just write this:

body {color: black;}

Just as sensible use of the cascade can help simplify your CSS, good use of inheritance can help to reduce the number and complexity of the selectors in your code. It you have lots of elements inheriting various styles, though, determining where the styles originate can become confusing.


0 Comments: