SVG Sprites: Free HTML & CSS Tutorial
Master SVG Sprites for Better Web Performance
Create reusable SVG sprite systems that combine multiple graphics into a single file, reducing HTTP requests and improving page load performance.
SVG Sprites Fundamentals
What is a Sprite?
A concept from video games where multiple small graphics are combined into a single file. SVG makes this technique even more powerful than pixel-based sprites.
Performance Benefits
Loading one file is faster than loading multiple files. Sprites reduce HTTP requests and improve page load times for users.
Reusability
Define once, use anywhere. SVG sprites can be referenced multiple times throughout your page with different styling applied.
Setup Requirements
Located in Desktop > Class Files > Advanced HTML CSS Class
This will be your main working file for the exercise
Should only show 'SVG Sprites' heading initially
You'll switch between them frequently during development
Creating the Sprite Definition
Create SVG Container
Add SVG tag with display='none' below the body tag to hide the definitions from view
Add Definitions Element
Insert <defs> tag inside SVG to store graphical objects for later use
Copy Icon Code
Open icon-twitter.svg and icon-facebook.svg files to copy their SVG code
Convert to Symbols
Change svg tags to symbol tags and add unique IDs for referencing
The <defs> element stores graphical objects that will be used later. Objects inside <defs> are not rendered directly - you must reference them with a <use> element.
The definition of our sprites is done, so now we can use them wherever we want in the page, and as many times as we want!
Implementing Sprite Usage
Reference with Use Element
Add SVG tag with <use> element pointing to sprite ID using xlink:href='#twitter'
Add CSS Class
Include class='social-icon' for styling purposes and better maintainability
Test and Verify
Save file and preview in browser to confirm the X logo appears below the heading
Add Additional Icons
Repeat the process for Facebook icon to demonstrate multiple sprite usage
CSS Styling Techniques
Size Control
Use width and height CSS properties instead of HTML attributes. Set both icons to 50px with 10px margin for consistent spacing.
Color Customization
Apply fill property to change SVG colors. Facebook icon uses #3b5998 blue while maintaining the ability to style each instance differently.
Individual Targeting
Use multiple classes for specific styling. Combine .social-icon.facebook selector to target individual sprite instances without affecting others.
No space between .social-icon.facebook means the element must have BOTH classes. With a space, it would target a .facebook element inside a .social-icon element.
Key Takeaways