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 HTML and CSS code. 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 theme.css and stored in a resources folder).

Here is the HTML code:

<html>
    <head>
        <title>Background colours and images</title>
        <link rel="stylesheet" href="theme.css" type="text/css"/>
    </head>

    <body>
        <div>
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum</p>
        </div>
    </body>
</html>

And here is the CSS code:

body{
    background-color: lightblue;
    background-image: url(image.png);
    background-size: 100%;
    background-repeat: no-repeat;
    background-attachment: fixed;
}

div{
    width: 500px;
    height: 500px;
    background-color: lightblue;
    background-image: url(image.png);
    background-size: 100%;
    background-repeat: no-repeat;

    /* You can also specify background position */
    /* if the background doesn't fill the div */
    background-position: center top;
}