Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> CSS

แสดงไอคอนจาก Image Sprite ด้วย CSS

Display Icon from Sprite: ใช้ Background-position แสดงส่วนของรูป

คล้ายบทก่อนแต่โฟกัสที่ไอคอนเดี่ยว (Twitter, Facebook) ใช้ background-position เลื่อกตำแหน่งใน sprite sheet

โค้ดตัวอย่าง

<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .twitter, .facebook {
      background: url(sprites_64.png) no-repeat;
      display: inline-block; width: 64px; height: 64px; margin: 10px 4px;
    }
    .facebook { background-position: 0 -148px; }
  </style>
</head>
<body>
  <h1>Image Sprite Example</h1>
  <a class="twitter"></a> <a class="facebook"></a>
</body>
</html>

Best Practices

  • ใช้ <a> หรือ <button> พร้อม aria-label สำหรับ accessibility
  • .icon { display: inline-block; width: 24px; height: 24px; background: url(sprite.svg) no-repeat; } – SVG sprite scaling ดีกว่า PNG
  • เพิ่ม background-size หาก sprite ใหญ่กว่าพื้นที่แสดง

SVG Sprite System (แนะนำ)

<svg style="display:none">
  <symbol id="twitter" viewBox="0 0 24 24"><path d="..."/></symbol>
  <symbol id="facebook" viewBox="0 0 24 24"><path d="..."/></symbol>
</svg>

<svg class="icon"><use xlink:href="#twitter"></use></svg>
<svg class="icon"><use xlink:href="#facebook"></use></svg>

.icon { width: 24px; height: 24px; fill: currentColor; }

SVG Sprite: scalable, stylable with CSS (fill, stroke), accessible, cacheable, single request