การทำให้รูปภาพเป็นลิงก์ ทำได้โดยการห่อแท็ก <img> ไว้ภายในแท็ก <a>
โครงสร้างพื้นฐาน
<a href="https://example.com"> <img src="image.jpg" alt="คำอธิบายรูป" width="200" height="100"> </a>
ตัวอย่าง
<!DOCTYPE html>
<html>
<head>
<title>HTML Image as link</title>
</head>
<body>
<p>The following image works as a link:<br>
<a href="https://www.qries.com/">
<img alt="Qries" src="https://www.qries.com/images/banner_logo.png" width="150" height="70">
</a>
</body>
</html>
Attribute สำคัญของ img
src- URL ของรูปภาพ (จำเป็น)alt- ข้อความทางเลือก (จำเป็นสำหรับ accessibility/SEO)width/height- ขนาดรูป (ช่วยป้องกัน layout shift)loading="lazy"- โหลดแบบ lazy loading (HTML5)
แนวทางปฏิบัติที่ดี
- ใส่
alt ที่อธิบายวัตถุประสงค์ของลิงก์ (ไม่ใช่แค่คำอธิบายรูป) - เพิ่ม
titleใน<a>สำหรับ tooltip - ใช้ CSS ควบคุมขนาดแทน width/height attribute สำหรับ responsive
- หลีกเลี่ยง border สีน้ำเงินรอบรูป (browser default) ด้วย
img { border: none; }