Tag Archives: spans

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>
<html>
<head>
 <title>Background images</title>
 <meta charset="utf-8"/>
 <link rel="stylesheet" href="resources/stylesheet4.css" type="text/css"/>
</head>
 
<body>
 
 <div>
 <h1>This is a heading</h1>
 <p>This is a paragraph</p>
 </div>
 
</body>
 
</html>

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

body{
 background-image:url("nepal.png");
 background-color:blue;
 background-repeat:no-repeat;
 background-attachment:fixed;
}
 
div{
 width:450px;
 height:300px;
 background-image:url("canada.jpg");
 background-repeat:no-repeat;
 background-position:center top;
}