Background images and colours

This tutorial explains how to add a background image to divs and the body section of your web page. It also explains how to have fixed background images (that don’t scroll with the content of your web page) and change the placement of background images. You will also see how to add background colours behind background images.

In the example image below, there is a div inside the body of the page. The body has a background image (a greyish gradient) while the div has a light green background.

Screen Shot 2017-04-14 at 4.30.34 pm

Watch the video below and then scroll down to see the sample code.

Below is the sample code for the HTML file. If you add more content to your page so that the page can scroll down, you will notice that the background image doesn’t move because it is set to a fixed position in the CSS code. Note that the HTML code refers to CSS in a separate stylesheet file (called stylesheet4.css and stored in a resources folder).

<!DOCTYPE html>
 <title>Background images</title>
 <meta charset="utf-8"/>
 <link rel="stylesheet" href="resources/stylesheet4.css" type="text/css"/>
 <h1>This is a heading</h1>
 <p>This is a paragraph</p>

Here is the sample code for the CSS file (it’s called stylesheet4.css and stored in a resources folder):

 background-position:center top;