Background images and gradients
One of the best ways to fancy up a site is to add a couple of background colors and images.
For that, we have two properties that we can use:
background-colorbackground-image
The background-color property is very straight forward, while background-image has a little more going on with it.
background-image
Section titled “background-image”background-image is an interesting property because we use it for images, but also for gradients.
However you are using it, the most important thing to remember with background-image is it’s decorational. Parts of the image may be cropped off, and are likely to be covered by other elements.
If an image is important, you probably want to use an <img> rather than a background-image, where you can also supply alternative text as well.
Images
Section titled “Images”To add a background image, we use the url() function, and then have a path to the image that we want to use. Unless you’re making a very quick demo, you’ll want your image to be locally hosted.
- index.html
Directorystyles
- style.css
Directoryassets
Directoryimages
- awesome-image.webp
- …
.hero { background-image: url(../assets/images/awesome-image.webp);}Controlling background images
Section titled “Controlling background images”When we declare a background image, by default it will:
- use it’s actual size
- be cropped if it’s bigger than the element
- tile, if it’s smaller than the element
We can control the size of it using background-size, where you can set two values, one for the width, and the second the height. There are times this can be useful, but it is easy to stretch and distort images.
Most of the time if I’m using background-size, it is to use either:
cover: Fills up the element. The image is allowed to be cropped.contain: Ensures that the entire image is visible. Will either be tiled, or leave empty space if repeating is turned off.
We can also use the background-position property, which allows us to set the x and y coordinates of the image. Like with background-size, I rarely use it like that, instead using the keywords:
topbottomleftrightcenter
You can provide two keywords, such as background-position: top center or background-position: bottom right, etc. When combined with background-size: cover, this allows us to pick the most important part of the image to stay in the frame.
And finally, we have background-repeat. By default, background images repeat along both axes. We can turn off repeating on one of the two, or both of them using:
no-repeat: Will not repeat.repeat-x: Only repeats on the x axis.repeat-y: Only repeats in the y axis.
Gradients
Section titled “Gradients”There are three different types of gradients. They all go from one color to another, but in different ways.
linear-gradient()radial-gradient()conic-gradient()
All three of them have the same basic functionality, where we can add a comma-separated list of colors inside the parenthesis, and it will create a gradient using those colors.