Inserting a background image

Go back to HTML and CSS Index

Credits

The image used in the following examples was downloaded from unsplash.com.

Photo by Ren Ran
unsplash-logoRen Ran

How to insert a background image

To insert a background image, you use the background-image property:

div {
background-image: url(img/unsplash.jpg);
min-height: 200px;
}
The background-image property applied to all div elements

background-image

In the example, the background image is added to all divs on the page. As you can see if you look at the original image, the only part visible is a small section of the top left corner.

To place the background image on the whole page, use body as the selector.

body {
background-image: url(img/unsplash.jpg);
}
The background-image property applied to the body element

The background-position property

If you want to change the section of the image to be shown, use the background-position property:

div {
background-image: url(img/unsplash.jpg);
background-position: center;
min-height: 200px;
}
The background-position property

background-image
background-position

As you can see from the example above, another section of the original image is now shown.

The background-size property

If you want the image to "fit" into the container that it's in, use the background-size property:

div {
background-image: url(img/unsplash.jpg);
background-position: center;
background-size: cover;
min-height: 200px;
}
The background-position property

background-image
background-position
background-size

As you can see from the example above, the full width of the image is now shown.

You can also use the value contain instead of cover, which will make for a different result:

div {
background-image: url(img/unsplash.jpg);
background-position: center;
background-size: contain;
min-height: 200px;
}
The background-position property

background-image
background-position
background-size

Not really ideal here, but you might find it useful in other scenarios.

The background-attachment property

By giving the background-attachment property the value fixed, the image won't scroll with the page:

div {
background-image:url(img/unsplash.jpg);
background-position: top center;
background-size: cover; background-attachment: fixed;
min-height: 200px;
}
The background-attachment property

background-image
background-position
background-size
background-attachment

This will give you a paralax-like effect. Cool right?

Assignment

  • Add a background image to an element on your page and play around with the other background properties.