CSS: the background-position property

Understanding how the background-position works in CSS is crucial to develop more complex techniques, such as rounded corners with images, CSS sprites and multiple backgrounds. In this post I'm going to explain how this property works in details.

X and Y coordinates

The syntax of the background-position property is as follows:

background-position: x y;

It accepts two values which represent the x and y axes. These axes, horizontal and vertical, specifies the coordinates to exactly position a background image. These coordinates start from the top left corner of the box having a background image.

Coordinate values

You can specify either a length or a keyword for both the values of the x and y coordinates. Lengths include:

  1. em
  2. pixels
  3. percentages

Keywords include:

  1. top
  2. bottom
  3. left
  4. right
  5. center

The following table maps keywords to their corresponding percentage equivalent:

Keywords and percentages
Keywords Percentages
top left 0 0
center top 50% 0
top right 100% 0
top center 0 50%
center center 50% 50%
right center 100% 50%
top bottom 0 100%
center bottom 50% 100%
right bottom 100% 100%

You can see how this work in the following picture:

As of CSS 2.1, you can combine lengths with keywords. However, Internet Explorer 6 doesn't support it.

Negative values

The offset of a background image is calculated as follows:

  • the x value moves the image from left to right
  • the y value moves the image from top to bottom

This is the default behavior of the background-position property. However, you can reverse this behavior by specifying negative values. So:

  • a negative x value moves the image from right to left
  • a negative y value moves the image from bottom to top

For example:

a.sprite {
 background: url(sprites.png) no-repeat 0 0;
}
a.sprite:hover {
 background-position: 0 -25px;
}

In the above example, we have the CSS sprites technique. If our sprite image is 50 pixels tall and both the sub-images are 25 pixels tall, then a negative value for the y axis will move the second sub-image to the top, thus creating a rollover effect.

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.