Background-Image

Background images can be added using CSS to save having all those <img src=…. in your mark up. In this brief tutorial, I shall explain how.

Firstly, I set up a very simple html page with some CSS.
HTML:
<div id=”#wrapper”>
content here…
</div>

CSS:
#wrapper {
width: 750px;
height: 600px;
border: 2px solid black;
margin: 0 auto;
}

The results are here. Nothing too glamorous so far. Now I add the CSS for the background image:
CSS:
background-image: url(ostrich.jpg);

Add that code to the #wrapper style. Obvously you need your own image. Mine is 750px x 500px. Now have a look. As you will see my image is repeating itself to make sure it fills the whole container. CSS does this by default so you need to tell it not to. Add this line:
CSS:
background-repeat: no-repeat;

Now have a look. The image no longer repeats. There are also 3 other repeats that CSS can do:
repeat-x (repeats in x axis (horizontal))
repeat y (repeats in y axis (vertical))
repeat (repeats in both directions)

And finally, I want to put my image in the center. Easy peasy! Add this:
CSS:
background-position: center;

Now check out the final version. That looks nicer! There are also other positions that the image can be placed in. They are:
top, left, right, center, bottom. They can also be mixed together, like so:
background-position: top left;
background-position: bottom right;

Good luck, and I hoped this tutorial has helped you.

Leave a Reply