Using classes in Cascading Style Sheets

At first glance Cascading Style Sheets (CSS) are the panacea for our formatting woes. If I want a paragraph to be highlighted in yellow, then I would just have to define a class, apply this to the element and away we go.

But there is the knub. It appears that while properties are inherited, classes are not. Thus a paragraph element <p> will inherit the properties from its generic block container <div> but not the class.

For example, the code

  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  2.  
  3. <html>
  4.  <head>
  5.   <style type="text/css">
  6.     #first { color: blue; }
  7.    .two { color: red; text-indent: 4em; }
  8.    p.three{ color:green; }
  9.   </style>
  10.  </head>
  11.  
  12.  <body>
  13.   <div id="first">
  14.    <p>This paragraph will inherit its properties from ID first and therefore be in blue</p>
  15.   </div>
  16.   <div class="two">
  17.    <p>This paragraph will be formatted using class two and be in red, indented 4 em because the style is inherited from the div element to which the style has been applied</p>
  18.   </div>
  19.   <div class="three">
  20.    <p>This paragraph will not be formatted using style three because the style definition only applies to the paragraph element with a class of three and classes are not inherited</p>
  21.    <p class="three">so the style is not applied unless the class is explicitly stated</p>
  22.   </div>
  23.  </body>
  24.  
  25. </html>

produces the following output

This paragraph will inherit its properties from ID first and therefore be in blue

This paragraph will be formatted using class two and be in red, indented 4 em because the style is inherited from the div element to which the style has been applied

This paragraph will not be formatted using style three because the style definition only applies to the paragraph element with a class of three and classes are not inherited

so the style is not applied unless the class is explicitly stated