CSS: body class and cascade

Most developers use class and ID selectors on the body element to add specific styles to specific pages. This is a recommended best practice that should be used either to have more control over the final layout or to give more control to your users thanks to user style sheets. However, as with many CSS techniques, this practice has been overused by many CMS applications so that now we can actually have a body element with several classes applied to it, such as <body class="class1 class2 classn"></body>. How these multiple classes are handled by browsers from a cascading perspective?

  1. if classes have no conflicting CSS rules, then the final styles will be the sum of all styles specified in each class:
    
    .class1 {
      font-size: 76%;
    }
    
    .class2 {
      background: gray;
    }
    
    .classn {
      padding: 1em;
    }
    
    
  2. if classes have conflicting rules, then the final styles will be calculated according to cascade and specificity, that is:
    1. declarations with the !important statement have the precedence over other rules
      .class1 {
        font-size: 76% !important; /* winner */
      }
      
      .class2 {
        font-size: 100%;
      }
      
      
    2. more specific selectors have the precedence over less specific selectors
      html body.class1 {
        font-size: 76%; /* winner */
      }
      
      body.class2 {
        font-size: 100%;
      }
      
    3. if the above points don't return a winner, then the class that comes later in the source will be the winner.
      .class1 {
        font-size: 76% !important;
      }
      
      .class2 {
        font-size: 100% !important; /* winner */
      }
      

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.