7

I've added all my icons into a sprite. Now, I need to show one icon from that sprite with a link. When I add the sprite and set its background position on the link all of the link's background is the sprite sprite. enter image description here

a{
    background-image:url('sprite.png'); 
}
.sprite_link_icon{
    padding-left: 20px;
    background-position: -36px -10px
}
<a class="sprite_link_icon" href="">test link test</a>

How do I set the sprite's width and height, so that it shows only one icon?

Is the only way to add two divs in the "a" tag? First, the div with sprite icon and width and height set, and in the other text?

<a href="">
    <div class="sprite_link_icon" style="width: 10px; height: 10px;"></div>
    <div>test link</div>
</a>
Josh Burgess
  • 9,327
  • 33
  • 46
lolalola
  • 3,773
  • 20
  • 60
  • 96

3 Answers3

3

You could use :before or :after to move the actual background to another (pseudo-)element that is exactly the right size of one icon.

Something like this:

.icon {
  /* nothing special here, just a dynamic element,
     maybe with a fixed height? */
}
.icon:before {
  content: '';
  display: inline-block;
  height: 16px;
  width: 16px;
  background: url(...) etc;
  margin-right: .25em; /* might not be necessary due to inline-block */
}

A fiddle: http://jsfiddle.net/rudiedirkx/RG3Kd/ (with wrong sizes, because I don't have a good sprite handy).

Rudie
  • 52,220
  • 42
  • 131
  • 173
  • This is the correct answer, as far as I'm concerned. No additional HTML, works back to IE7 and easily reconfigurable should the sprite size need to change. – Josh Burgess May 06 '13 at 19:17
0

You can't do it like, when you are doing sprites you should have mind how much will the width and the height of the element will be.

You can get out of the problem when you add a span in the "a" tag and add the backgroud to it, with specific width and height. Or you can rearrange your sprite.

drip
  • 12,378
  • 2
  • 30
  • 49
0

Use this code in style:

a
    {
        background-color:#00cc00;
        padding-left:20px;
        }

    a span
    {
        background-color:#fff;            
        }    

then this html:

<a href="#"><span>test link</span></a>