Chapter 14: CSS Background Colour

You can apply CSS to any element where it will make sense. If I wanted to set the background colour of the entire page, I would need to style the body element, as the body of the HTML represents the overall container for the web-page. To do this, I insert the following into my stylesheet.

body
{
background-color: black
}

Quite simple eh? The above tells the browser I want a black background. If I wanted all of the headings in my web-page to have a red background, I could do the following:

h1,h2,h3,h4,h5,h6
{
 background-color: red
}

Headings would now have a red background behind their text, instead of the default black.

See how I've specified a red background for all of the headings in my document? If you want to apply the same style to more than one element, you can do it in one go as above. Just remember to separate each element with a comma.

A Word on Colours

You can also specify an exact colour, by choosing the exact amount of red, green and blue that you require (in that order). Converting the above examples to this method would look like this:

<p style="background-color:rgb(0,255,0);">black text.. green background... woo!</p>

Output...

black text.. green background... woo!

<p style="background-color:rgb(0,255,0);">red paragraph of text. useful for expressing anger</p>

Output

red paragraph of text. useful for expressing anger

See how 0 represents absence of a red, green or blue, and 255 represents the maximum amount of that colour? You can also refer to my colour table for a range of colours complete with the rgb code's to be copied directly into your CSS!

Always remember to use the American spelling of "colour", which is "color". Admittedly it is faster to type, and I guess to read too...

And now, try setting the background colour yourself! Then see if you can remember this chapter's teachings, with the top of chapel quiz.