lolalola
lolalola

Reputation: 3823

get image from sprite and add into a href

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>

Upvotes: 7

Views: 1887

Answers (3)

user2089789
user2089789

Reputation:

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>

Upvotes: 0

drip
drip

Reputation: 12933

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.

Upvotes: 0

Rudie
Rudie

Reputation: 53881

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).

Upvotes: 3

Related Questions