CSS Background Color

In this tutorial we'll cover the basics of adding background colors using CSS to elements with fixed and variable widths. As a bonus we'll also demonstrate how to create perfect responsive color squares with just a few lines of code!

Body background color

In CSS the background is considered to be the width and height of an element, plus any padding and borders (but not margins). Using the CSS background-color property we can color the <body> background of our HTML page red.

<head> <style> body { background-color: #FF0000; } </style> </head> <body> </body>

Pretty simple, right! Of course, you could always use an ID or class to give the <body> element a background color, but this is the easiest method. Next we'll look at a couple techniques to color the background of in-page elements like a <div>.

Fixed size element background color

For HTML elements that are of a fixed size – whether in pixels, ems or percentages – adding a background color is easy. We can simply use the CSS code from the previous step to give our <div> of fixed width and height a blue background.

<head> <style> div { width: 50%; height: 200px; background-color: #00FF00; } </style> </head> <body> <div></div> </body>

If we remove either the height or width from the CSS code however, the background color will disappear. Try it for yourself in the demo.

Variable size element background color

Ok great, but what if we don't know the size of our HTML element? As long as there is an element inside the one you want to add a background too, we can use the CSS padding property to give the outer element some color.

<head> <style> div { padding: 16px; background-color: #00FF00; } </style> </head> <body> <div> <h1>Title with a background color</h1> </div> </body>

Responsive color squares

This technique uses a combination of positioning and fixed width with padding to create a perfect responsive square with a background color. You can actually create rectangles of any proportion just by varying the CSS padding-bottom property.

<head> <style> .outer { position: relative; width: 25%; padding-bottom: 25%; } .inner { position: absolute; width: 100%; height: 100%; background-color: #00FF00; } </style> </head> <body> <div class="outer"> <div class="inner"></div> </div> </body>

If you found this helpful be sure to check out our other tutorials on CSS text color, link color and placeholder color.