Reputation: 463
I've got some code that uses sprites, this is designed to look like a horizontal navigation bar. My question is: for my code shown below, does this method actually cause the end user to download the png image 8 times or just the once.
And if it is actually once, is there a better method to do this?
CSS Code
#facebook, #twitter, #linkedin, #googleplus {
width: 64px;
height: 64px;
display: inline-block;
}
#facebook {
background: url("images/sprite.png") 0 0;
}
#twitter {
background: url("images/sprite.png") -64px 0;
}
#linkedin {
background: url("images/sprite.png") -128px 0;
}
#googleplus {
background: url("images/sprite.png") -192px 0;
}
#facebook:hover {
background: url("images/sprite.png") 0 -64px;
}
#twitter:hover {
background: url("images/sprite.png") -64px -64px;
}
#linkedin:hover {
background: url("images/sprite.png") -128px -64px;
}
#googleplus:hover {
background: url("images/sprite.png") -192px -64px;
}
HTML Code:
<nav>
<a id="facebook" href="https://www.facebook.com"></a>
<a id="twitter" href="https://www.twitter.com"></a>
<a id="linkedin" href="https://www.linkedin.com"></a>
<a id="googleplus" href="https://plus.google.com"></a>
</nav>
Upvotes: 2
Views: 172
Reputation: 9664
It'll be downloaded only once, and this is the main reason to use CSS sprite sheets, it will be downloaded once only and with only one HTTP request instead of 8 HTTP requests if you provide an image for each icon with normal and hover states.
And no, this is how it is implemented and you're doing it correctly.
Resources:
Edit:
As Praveen Kumar mentioned you only write the url()
once for all corresponding rules and with background-position
shift the image either horizontally or vertically depending on your image
Upvotes: 4
Reputation: 167220
The request will happen only once and the image will be cached. The image will be redrawn again, but not by requesting the server. It requests the server only once. But it is always a good practise to have the url()
in the master class or a single instance:
#facebook, #twitter, #linkedin, #googleplus {
background: url("images/sprite.png");
}
Moreover it is better to use background-position
alone, instead of background
, also you don't need to reuse the background: url()
again in :hover
.
Upvotes: 4