In this tutorial, we will cover the basics of adding background colors to elements using CSS, including both fixed and variable widths. Background colors can dramatically affect the visual appeal of your website and improve user experience. As a bonus, we'll demonstrate how to create perfect responsive color squares with just a few lines of code, allowing you to design flexible layouts that adapt beautifully to any screen size!
In CSS, the background is defined by the width and height of an element, plus any padding and borders (but not margins). Using the CSS background-color property, we can easily set the <body> background of our HTML page to red, which serves as a strong visual anchor for the entire page.
html
<head>
<style>
body { background-color: #FF0000; }
</style>
</head>
<body>
</body>
Pretty simple, right? While you could use an ID or class to give the <body> element a background color, this is the easiest method and works well for basic styling. Next, we will explore techniques to color the backgrounds of in-page elements like a <div>, which can provide visual organization to your content.
For HTML elements with a fixed size—whether defined in pixels, ems, or percentages—adding a background color is straightforward. We can use the same CSS code from before to give our <div> a blue background, creating a clear distinction between different sections of our webpage.
html
<head>
<style>
div {
width: 50%;
height: 200px;
background-color: #00FF00;
}
</style>
</head>
<body>
<div></div>
</body>
However, if we remove either the height or width from the CSS code, the background color will disappear. This highlights the importance of defining dimensions for elements that require a visible background color. Try it out in the demo to see how it works in real-time!
Great! But what if we don't know the size of our HTML element? As long as there is an inner element within the one you want to color, we can use the CSS padding property to give the outer element some color. This approach allows for dynamic content while still maintaining a cohesive design.
html
<head>
<style>
div {
padding: 16px;
background-color: #00FF00;
}
</style>
</head>
<body>
<div>
<h1>Title with a Background Color</h1>
</div>
</body>
This technique combines positioning and fixed width with padding to create perfect responsive squares with a background color. You can create rectangles of any proportion by varying the CSS padding-bottom property. This is especially useful for creating visually appealing layouts that maintain their shape and size regardless of the viewport.
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>