CSS Image Sprite gộp nhiều icon/hình nhỏ vào 1 file ảnh lớn, dùng background-position để hiển thị phần cần thiết. Giảm HTTP requests, tăng tốc độ load.
Ví dụ mã nguồn (Cải tiến - sprite giả định)
<!DOCTYPE html>
<html>
<head>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; margin: 0; }
nav {
background-color: #1a1a2e;
padding: 15px 20px;
display: flex;
align-items: center;
gap: 20px;
}
nav a { color: white; text-decoration: none; font-size: 18px; font-weight: 500; transition: color 0.2s; }
nav a:hover { color: #4ecdc4; }
/* Sprite icons - giả định sprite.png 64x64, grid 32x32 */
.nav-icon {
display: inline-block;
width: 24px; height: 24px;
background-image: url('sprite.png'); /* File sprite thực tế */
background-size: 96px 32px; /* 3 icons ngang */
vertical-align: middle;
margin-right: 8px;
}
.icon-home { background-position: 0 0; }
.icon-home:hover { background-position: 0 -32px; } /* Hover state */
.icon-phone { background-position: -32px 0; }
.icon-phone:hover { background-position: -32px -32px; }
.icon-user { background-position: -64px 0; }
.icon-user:hover { background-position: -64px -32px; }
.icon-search { background-position: -96px 0; } /* Nếu có cột 4 */
.icon-search:hover { background-position: -96px -32px; }
</style>
</head>
<body>
<nav>
<a href="#"><span class="nav-icon icon-home"></span>HOME</a>
<a href="#"><span class="nav-icon icon-phone"></span>Call Us</a>
<a href="#"><span class="nav-icon icon-user"></span>Our Team</a>
<a href="#"><span class="nav-icon icon-search"></span>Search</a>
</nav>
<h1>Main content here</h1>
<p>Lorem ipsum dolor sit amet...</p>
</body>
</html>
Cách tạo Sprite Sheet
- Gom các icon cùng kích thước (ví dụ 32x32) vào 1 file PNG (ngang hoặc dọc)
- Đo vị trí từng icon (x, y)
- Set
background-size= tổng kích thước sprite sheet - Set
background-positionâm để dịch chuyển
Công cụ tạo Sprite
- Online: Sprite Cow, Toptal CSS Sprite Generator, SpriteGen
- Build tools: webpack-spritesmith, gulp-sprite, postcss-sprites
- Design tools: Figma (Export → Sprite), Sketch, Adobe XD
Hiện đại: SVG Sprite / Icon Fonts / SVG Inline
Sprite PNG vẫn dùng nhưng xu hướng hiện đại:
- SVG Sprite (
<symbol>+<use>): Vector, scale tốt, style được bằng CSS (fill, stroke) - Icon Fonts (Font Awesome, Material Icons): Dễ dùng, nhưng FOUC, accessibility issues
- Inline SVG: Kiểm soát hoàn toàn, không request thêm, tốt nhất cho icon ít
So sánh
| Phương pháp | Ưu điểm | Nhược điểm |
|---|---|---|
| PNG Sprite | 1 request, cache tốt, hỗ trợ cũ | Raster (mờ khi zoom), cố định màu, khó maintain |
| SVG Sprite | Vector, style CSS, 1 request, accessible | Cần build step, IE cần polyfill |
| Icon Font | Dễ dùng như text, scale tốt | FOUC, screen reader issues, ligature conflicts |
| Inline SVG | Full control, no request, animate được | Lặp HTML, cache kém |