Learning Code


Background Images

Previously we've added background-color but there are additional background properties which include:

background-image - adds an image in the background
background-position - positions the background image
background-repeat - controls how/if the image repeats in the background


To use the other background properties, first there must be a background image:
section {background-image: url('images/sprite.gif');}


Values include left, right, top, bottom, center, %, inherit and initial. The first value represents the horizontal placement while the second value represents the vertical placement:
section {background-position: top right;} or section {background-position: 0 50%;}


Values include repeat (repeats horizontally and vertically), repeat-x (repeats horizontally), repeat-y (repeats vertically), initial, inherit and no-repeat. This can look like:
section {background-repeat: no-repeat;} or section {background-repeat: repeat-x;}

Image Sprites

Sometimes you may want to have multiple states of one image. Combining images into one file often creates a slightly smaller file size and then only one image needs to be requested by the browser - this saves loading time.

In the HTML, add a transparent image (.gif or .png) where you want the image sprite positioned.

In the CSS, use the background property:
#sprite {width: 50px; height: 50px; background: url('images/sprite.gif') 0px 0px;}
The width and height are set to the size of my image section. I set the position of the image to 0px from the left and 0px from the top. When I want to show a different section of my image, I just need to change the position values.

Link States and Image Sprites

Perhaps you have an image link where you want the image to change if you are hovering or if you have visited the link. If your navigation bar is made up of image links, image sprites will be very helpful!

This example assumes that there is an id called top somewhere on the HTML page. In the HTML the code looks like:

In the CSS, the code could look like:
#sprite1 {width: 50px;height: 50px; background: url('images/sprite.gif');}
a:link #sprite1 { background-position: 0 0;}
a:hover #sprite1 {background-position: -50px 0px;}
a:active #sprite1 {background-position: 50px 0px;}

Can you use the Try-it Editor to try out these concepts?