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

Hiển thị Icon từ Image Sprite với CSS

Kỹ thuật Image Sprite: gộp nhiều icon vào 1 file ảnh, dùng background-position để crop hiển thị icon mong muốn.

Ví dụ mã nguồn

<!DOCTYPE html>
<html>
<head>
<style>
  body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; padding: 20px; }
  .social-icon {
    display: inline-block;
    width: 64px;
    height: 64px;
    background: url('sprites_64.png') no-repeat; /* Sprite sheet 64x64 per icon */
    margin: 10px;
    transition: transform 0.2s, opacity 0.2s;
  }
  .social-icon:hover { transform: scale(1.1); opacity: 0.8; }
  
  /* Vị trí trong sprite sheet */
  .twitter { background-position: 0 0; }      /* Icon 1: (0, 0) */
  .facebook { background-position: 0 -148px; } /* Icon 3: (0, -148) - bỏ qua icon 2? */
  .instagram { background-position: -64px 0; } /* Icon 2: (-64, 0) */
  .linkedin { background-position: -64px -64px; }
  .youtube { background-position: -128px 0; }
  .github { background-position: -128px -64px; }
</style>
</head>
<body>
<h1>Image Sprite Icons</h1>
<a href="#" class="social-icon twitter" aria-label="Twitter"></a>
<a href="#" class="social-icon facebook" aria-label="Facebook"></a>
<a href="#" class="social-icon instagram" aria-label="Instagram"></a>
<a href="#" class="social-icon linkedin" aria-label="LinkedIn"></a>
<a href="#" class="social-icon youtube" aria-label="YouTube"></a>
<a href="#" class="social-icon github" aria-label="GitHub"></a>
</body>
</html>

Quan trọng: Accessibility cho Icon-only Links

Vì <a> rỗng (chỉ có background), bắt buộc thêm:

  • aria-label="Tên mạng xã hội" cho screen reader
  • Hoặc <span class="sr-only">Twitter</span> bên trong (CSS ẩn visually)
  • title="Twitter" tooltip cho mouse hover

CSS Sprite vs Data URI vs SVG

Phương phápRequestCacheScaleStyle CSSPhù hợp
PNG Sprite1TốtKém (mờ)Khó (chỉ filter)Icon nhỏ, cố định, nhiều icon cùng lúc
Data URI (base64)0 (inline CSS)CSS cacheKémKhóIcon rất ít, critical CSS
SVG Sprite ()1TốtTuyệt vờiFill, stroke, transformHiện đại, responsive, accessible
Inline SVG0 (inline HTML)KhôngTuyệt vờiHoàn toànIcon ít, cần animate/interact

SVG Sprite Example (Khuyến nghị hiện đại)


/* sprite.svg */
<svg xmlns="https://www.w3.org/2000/svg" style="display:none">
  <symbol id="twitter" viewBox="0 0 24 24"><path d="M23 3a10.9 10.9 0 01-3.14 1.53..."/></symbol>
  <symbol id="facebook" viewBox="0 0 24 24"><path d="M18 2h-3a5 5 0 00-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 011-1h3z"/></symbol>
</svg>

/* HTML */
<svg class="icon"><use xlink:href="sprite.svg#twitter"></use></svg>

/* CSS */
.icon { width: 24px; height: 24px; fill: currentColor; }
.icon:hover { fill: #1da1f2; }