How to set a background image with CSS

Setting a background image with CSS shorthand is rather simple.

Setting the background of a DIV tag

In our example, we have a div with a class of “box” that we want to have an image background. In our CSS, we write the following:

.box { background: url(images/background.gif) no-repeat; }

Easy, right?

You just replace the images/background.gif with the URL to your image. The no-repeat line causes it to only appear once. The other options here are “repeat”, “repeat-x” (horizontal) and “repeat-y” (vertical).

Setting the background of BODY tag

You have a cool website but want a repeating fading from white to blue (top to bottom) in the background. You will find that setting your gradient like the following will give you that gradient across the top.

body { background: url(images/gradient.gif) repeat-x; }

But you will find something unpleasant about this. Once the image is done, there is an abrupt line and the page is white again. The answer is NOT to have an enormously long image but to add the exact color of blue that it ends at to the body tag itself.

body { background: #HEXNUM url(images/gradient.gif) repeat-x; }

Where it says HEXNUM you will enter the 6 digit Hex number to the color you want the body background to be.

Shifting the background image

You can determine where the background image will start and end by adding a few simple words:

.box { background: url(images/gradient.gif) right bottom repeat-x; }

This means that the background will start at the bottom right of whatever tag it is effecting. You can switch these between bottom and top, right, and left. (or you can enter pixel amounts)

Happy backgrounding!

Categorized in:

Tagged in: