Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> CSS

Thiết lập ảnh làm border cho phần tử với CSS border-image

Giới thiệu

Thuộc tính shorthand border-image cho phép thiết lập tất cả các thuộc tính border-image trong một dòng. Cú pháp đầy đủ:

border-image: <source> <slice> / <width> / <outset> <repeat>;

Ví dụ: 3 mức độ dày border khác nhau

<!DOCTYPE html>
<html>
<head>
  <style>
    .border-demo {
      border: 10px solid transparent;
      padding: 15px;
      margin: 10px 0;
      border-image-source: url(/css/images/border.png);
      border-image-repeat: round;
      border-image-slice: 30;
    }
    #borderimg1 { border-image-width: 10px; }
    #borderimg2 { border-image-width: 20px; }
    #borderimg3 { border-image-width: 30px; }
  </style>
</head>
<body>
  <p id="borderimg1" class="border-demo">Border image width: 10px</p>
  <p id="borderimg2" class="border-demo">Border image width: 20px</p>
  <p id="borderimg3" class="border-demo">Border image width: 30px</p>
</body>
</html>

Cú pháp shorthand chi tiết

Thành phầnThuộc tính tương ứngBắt buộc
<source>border-image-sourceCó
<slice>border-image-sliceCó
/ <width>border-image-widthKhông (mặc định: 1 = border-width)
/ <outset>border-image-outsetKhông (mặc định: 0)
<repeat>border-image-repeatKhông (mặc định: stretch)

Ví dụ shorthand gọn

/* Cú pháp tối giản */
border-image: url(border.png) 30 round;

/* Có width */
border-image: url(border.png) 30 / 20px round;

/* Đầy đủ */
border-image: url(border.png) 30 40 30 40 / 20px 30px / 5px round stretch;

Lưu ý quan trọng

  • Phải khai báo border hoặc border-width trước (có thể transparent)
  • Thứ tự: slice / width / outset repeat — dấu slash (/) phân cách width/outset
  • outset mở rộng vùng border ra ngoài box model (không ảnh hưởng layout)
  • Hỗ trợ gradient: border-image: linear-gradient(45deg, red, blue) 1;

Ứng dụng thực tế

  • Khung ảnh decorative (frame ảnh cổ điển, viền gỗ, kim loại)
  • Button gradient border hiện đại
  • Progress bar với border động
  • Card hover effect với border animated