คุณสมบัติ border-image ใน CSS ค่อนข้างซับซ้อน บทความนี้อธิบายว่าคืออะไร วิธีใช้ และข้อควรระวังกับเบราว์เซอร์ต่างๆ
โครงสร้าง Border Image (Shorthand)
border-image: url("image.jpg") /* source */ 25% / /* slice */ 70px / /* width */ 2px /* outset */ stretch; /* repeat */
ประกอบด้วย 5 longhand properties:
- border-image-source: URL รูปภาพหรือ gradient
- border-image-slice: ตัดภาพเป็น 9 ส่วน (4 มุม, 4 ขอบ, 1 กลาง) ใช้ % กำหนดตำแหน่งตัด ค่า
fillใช้ส่วนกลางด้วย - border-image-width: ความกว้างขอบภาพ ใช้ % หรือ rem/em/px ระบุได้ 4 ด้าน
- border-image-outset: ระยะห่างจาก border box ของ元素 (box model: ระหว่าง padding และ margin) ค่ายิ่งมาก ยิ่งห่าง
- border-image-repeat: พฤติกรรมขอบ (ไม่รวมมุม) ค่า:
stretch,repeat,round,spaceระบุได้ 1-2 ค่า
ข้อควรระวังกับเบราว์เซอร์ (Browser Quirks)
- Firefox, Safari: ใช้ longhand properties แยกกันได้
- Chrome: ต้องใช้ shorthand
border-imageร่วมกับborder-style(เช่นsolid) ถึงจะแสดงผล
ตัวอย่างโค้ด
.border-image-box { /* Firefox, Safari only */ border-image-source: url(...); border-image-slice: 25%; border-image-width: 70px; border-image-outset: 2px; border-image-repeat: round; }
.border-image-shorthand { /* All browsers */ border-style: solid; border-image: url(...) 25% / 70px / 2px round; }
สรุป
border-image เป็น shorthand ของ source, slice, width, outset, repeat เพื่อความเข้ากันได้ทุกเบราว์เซอร์ ควรตั้ง border-style: solid ก่อนระบุค่า border-image