HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

CSS Image Sprites

CSS image sprites are a technique used in web development to combine multiple images into a single image file. This single image file is then utilized as a background image for HTML elements, and specific portions of the image are displayed by adjusting the element's background position using CSS.

The primary purpose of using image sprites is to reduce the number of server requests made when loading a web page. Instead of requesting multiple individual images, the browser only needs to download a single image file, which can significantly improve page loading times, especially for websites with many small images like icons or buttons.

To use CSS image sprites, you typically define a CSS class for each image within the sprite. By adjusting the background position of the element using CSS properties like background-position, you can display the desired portion of the sprite image.

Example

.icon {
        width: 50px;
        height: 50px;
        background-image: url('sprites.png');
    }

    .icon-facebook {
        background-position: 0 0; 
    }

    .icon-twitter {
        background-position: -50px 0; 
    }
    
    <body>
        <div class="icon icon-facebook"></div>
        <div class="icon icon-twitter"></div>
    </body>
You can click on above box to edit the code and run again.

Output


In this example, sprites.png is the sprite image file containing both the Facebook and Twitter icons. The .icon class is applied to all elements, and additional classes like .icon-facebook and .icon-twitter specify the background position for each icon within the sprite.