Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> CSS

Tạo Navigation Menu với CSS Image Sprite

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

  1. Gom các icon cùng kích thước (ví dụ 32x32) vào 1 file PNG (ngang hoặc dọc)
  2. Đo vị trí từng icon (x, y)
  3. Set background-size = tổng kích thước sprite sheet
  4. 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ểmNhược điểm
PNG Sprite1 request, cache tốt, hỗ trợ cũRaster (mờ khi zoom), cố định màu, khó maintain
SVG SpriteVector, style CSS, 1 request, accessibleCần build step, IE cần polyfill
Icon FontDễ dùng như text, scale tốtFOUC, screen reader issues, ligature conflicts
Inline SVGFull control, no request, animate đượcLặp HTML, cache kém