Pages

Labels

Powered by Blogger.
Sunday, September 2, 2012

Adding a class or an ID to the body tag


One interesting way to use specificity  is to apply a class or an ID to the body tag. By doing this, you can then override styles on a page-by-page or even a site-wide basis. For instance, if you wanted all your news pages to have a specific layout, you could add a class name to the body element and use it to target your styles:



body.news {
  /* do some stuff */
}

<body class="news">
  <p>My, what a lovely body you have.</p>
</body>

Sometimes, you’ll need to override these styles on a particular page, such as your news archive page. In this case, you can add an ID to the body tag to target that specific page.

body.news { 
  /* do some stuff */ 


body#archive {
  /* do some different stuff */
}

<body id="archive" class="news">
  <p>My, what a lovely body you have.</p>
</body>

Using a class for the type of page and an ID for the specific page gives you a huge amount of control over the design and layout of your site. As such, this is one of my favorite techniques for writing maintainable code.

0 Comments: