How to Add a Background Image to a Website
This guide walks through how to add a background image to a website using the CSS background attribute.
Guide Tasks
  • Read Tutorial
  • Watch Guide Video
Video locked
This video is viewable to users with a Bottega Bootcamp license

So far, we've learned how to lay a background color and do animations with it. In this video, we're going to see how we can add a background image to a website.

Open styles.css and to have an image as the background for the entire page, go to body tag, and type this,

background: url('../../img/teslas.jpg'); 

Notice, the URL option contains the exact path using which we can traverse to the desired image. We're using the .. option to move back one directory, so we can retrieve the image we want. This URL will change depending on where you've kept your image files, but remember that you have to use two dots to move up one directory.

large

This image needs resizing because the focus of this image is not visible.

So, let's say no-repeat as we don't want a tiled wallpaper-like image, and we'll move it to the center. The code is:

body {
  font-family: sans-serif;
  color: #ab3939;
  background: url('.../.../img/teslas.jpg') no-repeat center center fixed;
}

So, the webpage now looks like this:

large

We can now see the vehicles.

Let's also shrink it further. We can do that with the code:

webkit-background-size: cover; 

This works for chrome and safari, but we'll have to fix it for Mozilla too, and for that:

 -moz-background-size: cover;

We'll also have the default background-size: cover;

body {
  font-family: sans-serif;
  color: #ab3939;
  background: url('.../.../img/teslas.jpg') no-repeat center center fixed;
  -webkit-background-size: cover;
  -moz-background-size: cover;
  background-size: cover;
}

So, this code makes our image look more appealing.

large

If you're wondering what cover is, it essentially tells the browser to shrink the image without changing the aspect ratio.

So, now you know how to grab an image and how to use it as a backdrop for a web page.

Resources