Changing page appearance using body id

So, you have a CSS based site and you would like an easy method that will allow you to change the appearance of individual pages?

This can be achieved with two easy steps:

  1. Add a class or an id to the body element of the page in question
  2. Use this class or id to override existing CSS rules.

A basic example

The HTML markup

<div id="container">
	<div id="header"></div>
	<div id="content"></div>
	<div id="foter"></div>

The basic CSS rules:

body { background: red; }
#container { background: white; }
#header h1{ color: red; }
#content { color: black; }
#footer { background: gray;  }

Changing the appearance of the “about” section

For the about section, we will add an ID to the body:

<body id="about">

Then we can override the basic CSS with some new rules:

/* Normal rules */
body { background: red; }
#container { background: white; }
#header h1{ color: red; }
#content { color: black; }
#footer { background: gray;  }

/* Rules for any page with "about" ID on body */
body#about { background: green; }
body#about #header h1{ color: green; }
body#about #content { color: purple; }
body#about #footer { background: brown; }

So, why will this work for any page with an ID of “about”?

One of the cascade rules states that if there is a conflict (where more than one CSS rule refers to the same element and property) then the one with more specificity will win.

Specificity is the score associated with each selector. Four scores are concatenated (linked together as a chain) to create a final score – a,b,c,d

  • A. Is there an inline style?
  • B. Count the number of IDs in the selectors.
  • C. Count the number of classes, attributes and pseudo-classes.
  • D. Count the number of element names or pseudo-elements.

body { background: red; }

The rule above has a score of 0,0,0,1 (it has one element in the selector), and it will win in most cases:

body#about { background: green; }

The rule above has a score of 0,1,0,1 (it has one ID and one element in the selector) and will beat the original rule whenever the “about” ID is present:

You can use this basic principle to change the entire appearance of pages or sections within your site.