CSS Background

6.10.2024
Copy

CSS Background

By Tony 6.10.2024
Favorite Share Report


Adding colors to text and paragraphs is one thing, but adding background colors to your website is even more common and useful. Even this article that you're reading has a gray background color, and the sidebar on the left has a darker shade of it. See, background colors are everywhere! Today, you'll learn how to add all kinds of backgrounds (not just colors) to your elements!

Background color

background-color: blue;

To add a background color to an element, use the "background-color" CSS property. Same as the "color" CSS property, you can set the value to a named color, a hex code, an rgb value, or an rgba value. Note that setting a background color will only give the element a background color, not the entire page.

Background image

background-image: url("image.png");

To make an element's background an image, use the "background-image" CSS property. For the value part, you need to use the "url" value function. Don't be scared of the name, because it's basically just a CSS program telling the browser where to find that background image. To use the "url" value function, just type "url", followed by a pair of parentheses, with the image path wrapped in there enclosed by double quotes, like in the example above.

Background gradient

background: linear-gradient(to right, red, blue);

Now we're getting real fancy with the background gradient. Gradient is basically the process of transforming a color to another one. To add it, use the "background" property (not "background-color"!), followed by another CSS function, "linear-gradient". There are three different values in this function: to right, red, and blue. The "to right" value is saying which direction the gradient is going. Red is the starting color, and blue is the ending one, meaning in this gradient, red is turning to blue going to the right. There can also be more than two colors, forming a more complex gradient.

Bonus: setting background image position

As you can see in the example above, the background image of the mountain is repeating and isn't centered properly. To fix this issue, you need to use two other CSS background properties: "background-size" and "background-position".

background-size: cover;
background-position: center center;

What "background-size: cover" does is that it enlarges the background image to scale until it fills the entire element, which gets rid of the repeating problem. But now the background image is enlarged, it's stretched and off centered, so we used the "background-position: center center" rule to set the image to the center. There are two centers because the first one sets the horizontal centering of the image, and the second one sets the vertical centering. Paste this code to the example above and see the CSS magic for yourself! You can also mess around with the values to learn about them and test them out!