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.
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>
To use image as a link in HTML, use the <img> tag as well as the <a> tag with the href attribute. The <img> tag is for using an image in a web page and the <a> tag is for adding a link. Under the image tag src attribute, add the URL of the image.
You create a defined area with a <a> with display:block; or <div> and use overflow hidden; to hide overflow and position:relative; . Then you place your <img> image sprite inside absolutely positioned, which is possible since you positioned the parent. Then use :hover on the image to change position.
Sprites are two-dimensional images which are made up of combining small images into one larger image at defined X and Y coordinates. To display a single image from the combined image, you could use the CSS background-position property, defining the exact position of the image to be displayed.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With