Overriding Inheritance


In the previous example, all elements were given the same font style through inheritance. Sometimes, however, children don't look like their parents. Not surprisingly, CSS also accounts for this. Say you want H1 elements to be in italic and the rest of the text to be normal. This is easily expressed in CSS:

 <style TYPE="text/css">   body { font-style: italic }   h1 { font-style-normal } </style> 

Because H1 is a child element of BODY (and therefore inherits from BODY), the two rules in the previous style sheet conflict with each other. The first one sets the font style of the BODY element and thereby also the font style of H1 through inheritance while the second one sets the font style specifically on the H1 element. Which rule will win? Let's find out by reviewing Figure 2.8.

Figure 2.8. The headline is normal while the other text is slanted.


The reason why the second rule wins is that it is more specific than the first. The first rule is extremely general it affects all elements on the canvas. The second rule affects only H1 elements in the document and is, therefore, more specific.

If CSS had been a programming language, the order in which the rules were specified would determine which one of them would win. CSS is not a programming language, and in the previous example, the order is irrelevant. The result is exactly the same if we use this style sheet:

 <style type="text/css">   h1 { font-style: normal }   body { font-style: italic } </style> 

CSS has been designed to resolve conflicts between style sheet rules such as this one. Specificity is one aspect of that. You can find the details in Chapter 13, "Cascading and inheritance."



Cascading Style Sheets(c) Designing for the Web
Cascading Style Sheets: Designing for the Web (3rd Edition)
ISBN: 0321193121
EAN: 2147483647
Year: 2003
Pages: 215

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net