A CSS sprite is a technique used in web development where multiple images are combined into a single larger image file. This approach helps reduce the number of HTTP requests required to load a webpage, as only one image is requested instead of multiple separate images. Using CSS, specific portions of the sprite image are displayed as needed by adjusting the background position, which improves page loading times and overall performance.
CSS sprites for raster images combine multiple bitmap images into a single file, with specific parts shown using CSS background-position
, which can lose quality when resized. In contrast, CSS sprites for SVG images use a single SVG file where individual graphics are referenced with the <use>
element and xlink:href
attribute, allowing for high-quality scaling and dynamic styling with CSS or JavaScript. SVG sprites offer greater flexibility and maintain visual clarity at any size compared to raster sprites.
Here you can find an example of SVG and HTML files as follows
<svg xmlns="http://www.w3.org/2000/svg" style="display: none;"> <!-- Tick Icon --> <symbol id="tick" viewBox="0 0 24 24"> <path d="M9 19l-7-7 1.41-1.41L9 16.17l11.59-11.59L22 6l-13 13z"/> </symbol> <!-- Cross Icon --> <symbol id="cross" viewBox="0 0 24 24"> <path d="M18 6L6 18M6 6l12 12" stroke="currentColor" stroke-width="2" fill="none"/> </symbol> <!-- Love (Heart) Icon --> <symbol id="love" viewBox="0 0 24 24"> <path d="M12 21.35l-1.45-1.32C5.4 15.36 2 12.28 2 8.5 2 5.42 4.42 3 7.5 3c1.74 0 3.41.81 4.5 2.09C13.09 3.81 14.76 3 16.5 3 19.58 3 22 5.42 22 8.5c0 3.78-3.4 6.86-8.55 11.54L12 21.35z"/> </symbol> <!-- Thumb Up Icon --> <symbol id="thumb-up" viewBox="0 0 24 24"> <path d="M2 21h4V9H2v12zm20-11c0-1.1-.9-2-2-2h-6.31l.95-4.57.03-.32c0-.41-.17-.79-.44-1.06L13.17 2 7.59 7.59C7.22 7.95 7 8.45 7 9v10c0 1.1.9 2 2 2h7c.78 0 1.48-.45 1.82-1.1l3.02-6.03c.09-.23.14-.47.14-.72v-1.5z"/> </symbol> </svg>
and
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>SVG Sprite Example</title> </head> <body> Here are CSS sprite SVG icons: <div> <object type="image/svg+xml" data="icons.svg" style="display:none;"></object> <svg style="width: 24px;height: 24px;"> <use xlink:href="icons.svg#tick"></use> </svg> <svg style="width: 24px;height: 24px;"> <use xlink:href="icons.svg#cross"></use> </svg> <svg style="width: 24px;height: 24px;"> <use xlink:href="icons.svg#love"></use> </svg> <svg style="width: 24px;height: 24px;"> <use xlink:href="icons.svg#thumb-up"></use> </svg> </div> </body> </html>
And here is the output
You cannot open this html file on your browser directly. It will not work. You will need to host it. If you have python already installed, one simple way is to run this command:
python3 -m http.server 8374
to host the current directory on port 8374 (or whatever port you want).