รูปภาพเป็นองค์ประกอบทั่วไปของหน้าเว็บ และเป็นวิธีดีสำหรับสร้างลิงก์ไปหน้าอื่น ด้วยการรวม anchor tags พร้อม href attribute และ image tags เราสามารถสร้างรูปภาพที่ทำงานเป็นลิงก์ระหว่าง 2 หน้า ทำได้ตามขั้นตอน:
- สร้าง div element จัดเก็บ image element, anchor tag และสิ่งอื่นๆ ที่อธิบายลิงก์
- สร้าง anchor tag
<a>มี hypertext references (href) ชี้ไปหน้าอื่น ตั้ง href เป็นไซต์/ไฟล์ที่ต้องการ - ระหว่างแท็ก
<a>เปิด/ปิด สร้าง<img>tag จำไว้ว่า image tags เป็น self-closing เพิ่มแอตทริบิวต์ src ชี้ URL/path ของรูปภาพสำหรับลิงก์ - สร้างสิ่งอธิบายรูปภาพเพื่อผู้ใช้รู้ว่าคลิกได้ อาจเป็น
<caption>,<div>,<h2>,<p>ตามต้องการ
ตัวอย่างทำงานอยู่ในโค้ดด้านลอง ลองเล่นดู!
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Image Link</title> <style> div { width: 500px; display: flex; flex-flow: column wrap; } img { width: 100%; } caption { width: 100%; height: 50px; } </style> </head> <body> <div> <a href="https://www.goldengate.org/" target="_blank" referrerpolicy="no-referrer"> <img src="https://images.unsplash.com/photo-1449034446853-66c86144b0ad?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=2100&q=80" alt="Golden Gate Bridge" refer/> </a> <caption> An icon in the San Francisco skyline, the Golden Gate bridge shines in the twilight night sky. Click the image to learn more information about the Golden Gate bridge. </caption> </div> </body> </html>
หมายเหตุสุดท้าย: น่าสนใจที่จะวาง <a> แค่รอบ caption – เพราะลิงก์อ้างถึงนั้น แต่ผู้ใช้คาดหวังว่าคลิกรูปภาพจะเปิดแท็บใหม่ไปยังปลายทาง (นี่คือ target="_blank") ดังนั้น ให้ <a> ห่อรูปภาพ และทิ้งข้อความอธิบายรูป – หรือวาง <a> ห่อทั้งข้อความและ <img> ทั้ง 2 วิธี可行