ใช้คุณสมบัติ border เพื่อเพิ่มเส้นขอบให้รูปภาพ (<img>)
ตัวอย่างโค้ด
<!DOCTYPE html> <html> <head> <style> img { border: 8px solid rgb(0, 238, 255); width: 400px; height: 400px; } </style> </head> <body> <h1>Border Around Image Example</h1> <img src="https://images.pexels.com/photos/34950/pexels-photo.jpg?auto=compress&cs=tinysrgb&dpr=2&h=650&w=940"> </body> </html>
คำอธิบาย
รูปภาพได้รับเส้นขอบ 8px สีฟ้าอ่อน (rgb(0, 238, 255)) ขนาดรูปถูกบังคับให้ 400x400px (อาจบิดเบือนถ้าอัตราส่วนไม่ตรง)
แนวทางปฏิบัติที่ดีสำหรับ Image Border:
1. รักษาอัตราส่วนภาพ (Aspect Ratio):
img {
border: 8px solid #00eeff;
width: 400px;
height: auto; /* หรือ max-width: 100%; height: auto; */
}
2. ใช้ Border-radius สำหรับมุมโค้ง:
img {
border: 8px solid #00eeff;
border-radius: 12px; /* หรือ 50% สำหรับวงกลม */
max-width: 100%;
height: auto;
}
3. Border Image (รูปภาพเป็นขอบ):
img {
border: 20px solid transparent;
border-image: url(border-pattern.png) 30 round;
max-width: 100%;
height: auto;
}
4. Box-shadow แทน Border (Modern):
img {
box-shadow: 0 0 0 8px #00eeff; /* inset ก็ได้ */
border-radius: 12px;
max-width: 100%;
height: auto;
}
5. Outline + Outline-offset (ไม่ส่งผล layout):
img {
outline: 4px solid #00eeff;
outline-offset: 4px;
border-radius: 12px;
max-width: 100%;
height: auto;
}
ตารางเปรียบเทียบวิธีสร้างขอบ:
| วิธี | ส่งผล Layout | Border-radius | รองรับ Gradient/Image |
|---|---|---|---|
border | ใช่ | ได้ | ได้ (border-image) |
box-shadow | ไม่ (paint only) | ได้ | ไม่ได้ (solid color only) |
outline | ไม่ | ได้ (แต่ outline ไม่โค้งตาม border-radius ในบาง browser) | ไม่ได้ |
border-image | ใช่ | ซับซ้อน | ได้ (หลัก) |