An image sprite is a single image that contains multiple smaller images.
A web page with numerous images can take a long time to load and generate multiple server requests.
Using image sprites reduces the number of server requests and conserves bandwidth.
Background Image Example
In this example, you'll learn how to use one single image ("sprites.png") as a background image for the next and previous links, instead of two separate images.
With CSS, we can display only the part of the image we need.
<a id="prev-link" href="/previous-page">Prev</a>
<a id="next-link" href="/next-page">Next</a>
#prev-link {
padding: 5px 13px 6px 45px;
background-color: #EEEEEE;
background-image: url('icon-left-right.png');
background-repeat: no-repeat;
background-position: 6% 107%;
text-decoration: none;
border-radius:5px;
}
#next-link {
padding: 5px 47px 7px 10px;
background-color: #EEEEEE;
background-image: url('icon-left-right.png');
background-repeat: no-repeat;
background-position: 88% -9%;
text-decoration: none;
border-radius:5px;
}
In this example, we are using the background-position
property to specify which portion of the image we need for each link element. This is the easiest way to use image sprites.
Hover Effect Example
In this example, you'll see how to use a single image to specify two different background images for normal and hover states of a link element.
<a id="link-btn" href="/">Link Element</a>
#link-btn {
color: #000000;
padding: 7px 10px 8px 37px;
text-decoration: none;
border-radius: 10px;
background-color: #EEEEEE;
background-image: url('sprites.png');
background-repeat: no-repeat;
background-position: 4% -74%;
}
#link-btn:hover {
color: #FFFFFF;
background-color: #000000;
background-position: 4% 155%;
}