CSS: use of background images

The first thing you need to bear in mind when dealing with CSS background images is the stacking order of the images. Images are stacked according to the source code order and relationship between parent and child elements. So the background image of the outermost element always covers the background images of the innermost one.

For example, if you want to stack four rounded corners using the old-fashioned technique of the four stacked divs, you have something like this:

#box {
    background: #eee url(img/top-left.gif) no-repeat 0 0;
}

#box-top-right {
    background: url(img/top-right.gif) no-repeat 100% 0;
}

#box-bottom-left {
    background: url(img/bottom-left.gif) no-repeat 0 100%;
}

#box-bottom-right {
    background: url(img/bottom-right.gif) no-repeat 100% 100%;
}

Notice that:

  1. The background-color of the box is set on the innermost element. If you set it on another of the four elements, the background color of the outermost element will cover the background image of the innermost one.
  2. The background-position property has been set using the x and y coordinates, respectively. So '0 0' means 'top left' and '100% 100%' means 'bottom right'. You can use also keywords, but you cannot mix up keywords and lengths (that's invalid).

When creating background images with your favorite image editor, always remember to handle transparencies very carefully. If your element has a given background color and your image as a transparent portion, then the background color of the element will fill the transparent portion (and sometimes this is not what you really want).

Another thing to keep in mind is how the external boundaries of your image are rasterized. For example, if you have a tiled background image with a gradient on an innermost element and a single background image with a transparent background on an outermost one, then you need to check if these two images combine gracefully. If transparency is not handled properly, you could get some undesired effect when it comes to stack both images over each other.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.