Floating Labels
CSS / HTML / Tips

Use of Image Sprites in CSS

Image Sprites
Use of Image Sprites in CSS

Image Sprites is a technique that can be useful when you have to write the same CSS with different background images like icons. For example, a single image which is containing multiple different graphics of the same size like icons, logos is called Image Sprite. It’s a good technique that helps to reduce the load time and prevent multiple server requests.

Let’s say we have to create a “Follow Us” section and put some social media icons so that users can click on the icons to go to your social media pages. In this case, we can use the Image Sprites technique. So first we will write some CSS which will be common for all icons.

CSS:

.icon {
   width: 55px;
   height: 55px;
   display: inline-block;
   margin-right: 5px;
   background-image: url(https://premium.wpmudev.org/blog/wp-content/uploads/2015/05/social-media-icons-css-sprite.png);
   background-repeat: no-repeat;
   background-position: 0px 0px;
}

And the HTML :

<h1>Follow Us:</h1>
<span class="icon fb-icon"></span>
<span class="icon twitter-icon"></span>
<span class="icon instagram-icon"></span>

Now if you check your page then you will notice that there is only one icon which is being repeated for all three span.icon tags. Now we will write some CSS for fb-icon, twitter-icon and instagram-icon. We will add different background-position for different icons.

You can set a different position for different icons by increasing and decreasing values by using your browser’s inspect element tool.

CSS for fb-icon, twitter-icon and instagram-icon:

.icon {
   width: 55px;
   height: 55px;
   display: inline-block;
   margin-right: 5px;
   background-image: url(https://premium.wpmudev.org/blog/wp-content/uploads/2015/05/social-media-icons-css-sprite.png);
   background-repeat: no-repeat;
   background-position: 0px 0px;
}

.fb-icon {
   background-position: -56px 0px;
}
.twitter-icon {
   background-position: 0px 0px;
}
.instagram-icon {
   background-position: -115px 0px;
}

Now check your page. Thanks for visiting.

Author

I am a Full Stack Web Developer. I have more than 8 years of experience in the web design and development industry.

Leave a Reply

Your email address will not be published. Required fields are marked *