You learned that background-color lays a color in the background. In fact, instead of a color, you can also lay an image. A photo spreading across a hero, a pattern laid faintly underneath — the background of a page with atmosphere is usually the work of this background-image.
Let’s write one
.hero {
background-image: url("photo.png");
}| Part | Meaning |
|---|---|
background-image | ”I’m laying an image in the background” |
url( ) | The container you put the image’s location into |
"photo.png" | The path to the image file |
The inside of url() is written the same way as the path you write in an <img> tag’s src.
Left alone, it gets tiled
If you say nothing, a background image gets repeated and tiled like tiles.
When you don’t want it to repeat, background-repeat: no-repeat; makes it just one.
.hero {
background-image: url("photo.png");
background-repeat: no-repeat;
}no-repeat stops the tiling and leaves just one.Spread it to fill: background-size
The most common use with a background photo is the setting that spreads it to fill the element.
.hero {
background-image: url("photo.jpg");
background-size: cover;
}background-size is the property that decides the size of the background image. You can specify it with a number like 48px, but the first one to learn is cover.
cover is the setting that “scales the image up or down to cover it completely, so no gaps appear.” Add background-position: center and it’s adjusted so the center of the image is visible.Besides cover, there’s also a value called contain. contain fits the whole image without cutting it, but gaps may appear in exchange. Use cover when you want the photo itself to be the star, and contain when you want to show something whole and clear, like a logo.
Summary of this lesson
background-image: url("path")lays an image in the background- Left alone it gets tiled. For just one, use
background-repeat: no-repeat - To spread a photo to fill the element, use
background-size: cover+background-position: center