CSS Background Color
This tutorial will go over the fundamentals of adding background colors with CSS to elements that have fixed or variable widths. As a special addition, we will also show you how to create perfectly responsive colored squares with just a few lines of code!
Body background color
In CSS, the background is defined as the width and height of an element, including any padding and borders (but excluding margins). By using the CSS background-color property, we can make the <body> background of our HTML page red.
Very simple, right? Of course, you could also use an ID or class to give the <body> a background color, but this is the most direct method. Next, we will explore a couple of techniques for coloring the background of in-page elements like a <div>.
HTML
<head>
<style>
body { background-color: #FF0000; }
</style>
</head>
<body>
</body>
Fixed size element background color
For HTML elements with a fixed size—whether in pixels, ems, or percentages—adding a background color is simple. We can use the CSS code from the previous step to give our fixed-width and fixed-height <div> a blue background.
However, if we omit either the height or width from the CSS code, the background color will not be visible. You can try this for yourself in the demo.
HTML
<head>
<style>
div {
width: 50%;
height: 200px;
background-color: #00FF00;
}
</style>
</head>
<body>
<div></div>
</body>
Variable size element background color
That's great, but what if we don't know the dimensions of our HTML element? As long as there is an element inside the one you want to color, we can use the CSS padding property to give the outer element a background.
HTML
<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 method uses a mix of positioning and fixed width with padding to produce a perfect responsive square with a background color. You can actually make rectangles of any aspect ratio just by adjusting the CSS padding-bottom property.
If you found this useful, be sure to explore our other tutorials on CSS text color, link color, and placeholder color.
HTML
<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>