CSS Background Images
A background image is a picture placed behind an element's content. The repeat, position and size properties steer how the picture fills the area.
Tile along the row
The small pattern picture fills the box. The repeat-x value tiles it along the row only.
.box {
background-image: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' width='20' height='20'><rect width='20' height='20' fill='%23dbeafe'/><circle cx='10' cy='10' r='4' fill='%233b82f6'/></svg>");
background-repeat: repeat-x;
}Show the picture once
The no-repeat value stops the tiling. The center value places the single picture in the middle of the box.
.box {
background-image: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' width='20' height='20'><rect width='20' height='20' fill='%23dbeafe'/><circle cx='10' cy='10' r='4' fill='%233b82f6'/></svg>");
background-repeat: no-repeat;
background-position: center;
}Cover the box
The cover value stretches the picture over the whole box. Parts of the picture can fall outside the box edges.
.box {
background-image: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' width='20' height='20'><rect width='20' height='20' fill='%23dbeafe'/><circle cx='10' cy='10' r='4' fill='%233b82f6'/></svg>");
background-size: cover;
}Example
.box {
background-color: lightblue;
background-image: url("data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' width='20' height='20'><rect width='20' height='20' fill='%23dbeafe'/><circle cx='10' cy='10' r='4' fill='%233b82f6'/></svg>");
background-repeat: no-repeat;
background-position: center;
background-size: cover;
}
h1 {
color: white;
background-color: blue;
}Key points
- background-image: the property that places a picture behind the content
- The picture paints over the background colour and under the content.
- background-repeat: the property that controls how the picture tiles
- background-position: the property that sets where the picture sits
- background-size: the property that sets the drawn size of the picture
- A picture that fails to load leaves the background colour showing.
In this example, the box first takes a light blue background colour. The pattern picture then paints over that colour. The no-repeat value keeps the picture to a single copy. The center value places it in the middle, and cover stretches it over the whole box. The h1 rule gives the heading a plain blue background for contrast.
Note
The background shorthand can set the image and its controls in one declaration.
Try it Yourself
Edit the code, then press Run.
Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
Which property stops a background picture from tiling?