Right aligned CSS sprites

The benefits of CSS sprites are well document.

  • Improved web site perfomance due to a reduced in http requests
  • Simple rollovers without JavaScript
  • Easy management of multiple images within one file.

Due to these benefits I find myself keen to use CSS sprites whenever I can. However, until recently there has been one situation where I found myself unable to add particular images to CSS sprites. Right aligned images.

When positioning a background image you set the top and left positions like so:

background-position:10px 30px

The first value represents the horizontal position and the second represents the vertical position. This example would move a background image 10px from the left and 30px from the top. You can use other units like relative numbers (%, em), or the length keyword combinations top, bottom, left, center, right.

Positioning images within a CSS Sprite you use the units (pixels or percentage) with a negative value

background-position: -10px -30px

I like to think of this as clipping an image, you are basically saying cut 10px from the left of my image and 30px from the top and show the rest of the image from that point in the the top left position. As you are using the positioning coordinates to “clip” the image you are unable to move the image position like you can with positive values. Here’s an example page of left aligned sprites.

This works for left aligned images however if you want the image to be right aligned things are a bit different. Although the W3C state you can’t do this, it is possible to combine units with lengths. You can use the keyword or percentage to get the right hand side of the image and pixels to get the top coordinate. e.g.

background-position: 100% -10px
or

background-position: right -10px

I have x-browser tested this technique in IE 5.5 upwards, FF 2 & 3, Opera and Safari on Mac and Windows and it works fine and the CSS still validates too. You can see the right aligned sprites on this demo page.

When the sprite contains multiple images positioned horizontally then the images to the left may get shown. What I tend to do is set up a seperate sprite for all images that are right aligned, though if you want to keep everything in one place you could just place all sprites vertically or make the sprite extra large and right align the appropriate images within the sprite with plenty of white space to the left.

This entry was posted on