Applying Background Images Using CSS

A background image can be applied to any element using the following CSS declaration:

background-image: url(image name);

Shorthand

Shorthand background declarations are written as:

background: color image repeat attachment position;

For example, the following code:

p {
  background-color: #f00;
  background-image: url(background.gif);
  background-repeat: no-repeat;
  background-attachment: fixed;
  background-position: center;
}

would be written in shorthand as:

p {
  background: #f00 url(background.gif) no-repeat fixed center;
}

Background Position

Two values can be used with the background-position property as follows:

p {
  background: #f00 url(background.gif) no-repeat fixed center left;
}

The first value, called the x-coordinate or x-position, is the horizontal-position or distance from the left. The optional second value, called the y-coordinate or y-position, is the vertical-position or distance from the top.

The top left corner, 0% 0%, is the default location. The right bottom corner is 100% 100%. If only one value is specified, it is assumed to be for the x-coordinate; the y-coordinate defaults to center or 50%.

Units of Measurement

Units of measurement, such as pixels, points, em units, etc., can be used for the background-position. Negative values are allowed too. Combinations of keyword, length, and percentages are also allowed (e.g., 50% 2em or 100px bottom or left 10%). For logical reasons, when using combinations of keyword and non-keyword values, left, right, and center should only be used for the x-coordinate; top, bottom, and center should only be used for the y-coordinate.

Don’t Forget Color

Always remember to specify a background color when using an image as a background, especially with light-colored text, because the text should be readable if the image fails to load.

Examples

x-pos x-pos y-pos x-pos y-pos x% y% Example
n/a top left left top 0% 0%
top top center center top 50% 0%
n/a top right right top 100% 0%
left center left left center 0% 50%
n/a center center center 50% 50%
right center right right center 100% 50%
n/a bottom left left bottom 0% 100%
bottom bottom center center bottom 50% 100%
n/a bottom right right bottom 100% 100%

One thought on “Applying Background Images Using CSS

  1. Ventego says:

    Very interesting.

Leave a Reply

Your email address will not be published. Required fields are marked *