2

CSS Sprite is useful, helps speed up loading time and performance. But I find they have certain limitations. I like to know whether there are ways around this or whether it is inherent and that they are limited.

For example: If I wanted an arrow icon on my anchor link to be on the right hand side:

a 
  display:block;
  padding:0 15px 0 0;
  background:transparent ("/images/arrow.gif") no-repeat scroll right top;
}
a:hover {
  background-position:-10px top;
}

This wouldn't actually work because I positioned the arrow icon to be on the right hand side of my anchor tag. But then how would I shift the image -10px when I still want it positioned on the right?

Steven Wu
  • 293
  • 1
  • 4
  • 13
  • Could you please clarify what is the expected behavior? There is no limitation as to where you can place images with sprites if the sprite image is correctly built. Also don't mix units such as right top with pixels as IE can have problems. – George Katsanos Feb 08 '12 at 11:22
  • Expected behaviour is to have the background icon to always be sitting on the right but when shifted on hover should still be there. Mohamed here has provided a solution to the problem – Steven Wu Feb 08 '12 at 12:16

1 Answers1

2

You can use the :after pseudo element to create an additional element after the link text but still inside the anchor tag by CSS, set it to equal size of each picture in your sprite, and then be able to use background position no problem.

Here is an example of doing this with a 4 images sprite, each of the images are sized 18px * 18px (I just found the pic online on google images, so, not even sure how long it'll be available):

To see the example live version: http://jsfiddle.net/Meligy/CLLau/

The important bits of the code:

a:after {
    content: " ";
    display:inline-block;
    width:18px;
    height:18px;
    overflow:hidden;
    vertical-align:middle;
    margin-left:0.5em;
    background: url(http://www.waterbobble.com/skin/frontend/bobble/default/images/round_arrow_sprite.gif);
    background-position: 0 0;
}

a:hover:after {
    background-position: 18px 18px;
}

Update:

This is supported in all current browsers, in IE, it's supported starting from IE8.

For a hack to support for IE 6, 7, check this other Stackoverflow reply:
:after and :before css pseudo elements hack for IE 7

Community
  • 1
  • 1
Meligy
  • 35,654
  • 11
  • 85
  • 109
  • This looks like the perfect solution. Thanks Mohamed. Will need to test this to make sure it works in older browsers – Steven Wu Feb 08 '12 at 12:15