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

วิธีสร้าง Border Images ใน CSS

Border Image: ใช้รูปภาพเป็นขอบแทนสี/เส้นธรรมดา

Property border-image ใช้รูปภาพตัดเป็น 9 ส่วน (9-slice: 4 มุม, 4 ขอบ, 1 กลาง) แล้ว scale/repeat/tile ตามขนาด border

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

<!DOCTYPE html>
<html>
<head>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .border1 {
      border: 10px solid transparent; padding: 15px;
      border-image: url("https://i.picsum.photos/id/677/200/300.jpg") 30 round;
    }
    .border2 {
      border: 10px solid transparent; padding: 15px;
      border-image: url("https://i.picsum.photos/id/677/200/300.jpg") 2% round;
    }
  </style>
</head>
<body>
  <h1>Border Image in CSS</h1>
  <p class="border1">Some random sample text inside the paragraph</p>
  <p class="border2">Some random sample text inside the paragraph</p>
</body>
</html>

Border-image Syntax (Shorthand)

border-image: source slice width outset repeat;
/* ตัวอย่าง */
border-image: url(border.png) 30 30 round stretch;
/* source: url | slice: 30px (หรือ %) | width: 30px | outset: 0 | repeat: round stretch */

Slice (การตัดรูป) - สำคัญที่สุด

  • 1 ค่า: ทุกด้านเท่ากัน
  • 2 ค่า: top/bottom, left/right
  • 3 ค่า: top, left/right, bottom
  • 4 ค่า: top, right, bottom, left (clockwise)
  • หน่วย: px (สำหรับ raster) หรือ % (สำหรับ vector/SVG) – % คำนวณจากขนาดรูป

Repeat Values

  • stretch (default) – ยืดขอบกลาง
  • repeat – ทайล์ซ้ำ (อาจหักขาด)
  • round – ทายล์ซ้ำแต่ scale ให้พอดี ไม่หักขาด
  • space – ทายล์ซ้ำแต่กระจาย space ให้พอดี

Browser Support

IE 11+, Edge, Chrome, Firefox, Safari – รองรับเต็มรูปแบบ (IE 11 ต้อง prefix -ms- สำหรับบางค่า)