Skip to content

CSS3 边框图片

CSS border-image 属性允许你使用一张图片作为元素的边框,提供了超越简单的实线或虚线边框的创意样式可能性。

border-image 属性现在已被所有现代网页浏览器广泛支持。对于此特性,不再需要供应商前缀。

border-image 如何工作:九宫格切片

Section titled “border-image 如何工作:九宫格切片”

border-image 属性的工作原理是将源图片切分成九个区域,就像一个井字格游戏板一样:

  1. 四个角部区域。
  2. 四个边缘区域(上、右、下、左)。
  3. 一个中部区域。

浏览器随后将这些区域应用于元素的边框区域:

  • 角部区域放置在元素的边框角上。
  • 边缘区域沿边缘重复、缩放或拉伸。
  • 中部区域通常被丢弃,或在指定了 fill 关键词时用于填充背景。

重要提示: 为了使 border-image 正确工作,元素通常需要一个非 none 的 border-style 和一个 border-width。通常使用透明边框(如 border: 10px solid transparent;)来定义绘制边框图片的区域,而不会显示下方的实色。

border-image 属性是以下几个独立属性的简写形式:

  • border-image-source:指定作为边框使用的图片的路径(url(...))。
  • border-image-slice:定义如何切片图片(使用数字或百分比)。
  • border-image-width:设置边框图片的宽度(可以与 border-width 不同)。
  • border-image-outset:指定边框图片区域超出边框盒(border box)的量。
  • border-image-repeat:控制边缘区域的平铺方式(stretch、repeat、round、space)。

round 值会重复边缘切片,并稍微调整其大小以完美贴合,不会出现裁剪。

/* Assume border.png is an image suitable for slicing */
#border-img-round {
border: 30px solid transparent; /* Define area for image */
padding: 15px;
border-image-source: url('border.png');
border-image-slice: 30; /* Slice 30px in from each edge */
border-image-repeat: round; /* Tile edges by rounding */
width: 200px;
height: 100px;
background-color: lightyellow; /* Show background behind padding */
}

stretch 值会拉伸边缘切片以填充空间。

/* Using the shorthand property */
#border-img-stretch {
border: 20px solid transparent;
padding: 15px;
border-image: url('border.png') 25 stretch; /* source slice repeat */
/* border-image-slice is 25, border-image-repeat is stretch */
width: 200px;
height: 100px;
background-color: lightcyan;
}

border-image-slice 的百分比是相对于源图片尺寸计算的。

#border-img-percent {
border: 25px solid transparent;
padding: 15px;
border-image-source: url('another-border.png');
border-image-slice: 20%; /* Slice 20% in from edges */
border-image-repeat: repeat; /* Tile edges by repeating */
width: 250px;
height: 120px;
background-color: lavender;
}
属性描述
border-image用于设置 border-image-source、border-image-slice、border-image-width、border-image-outset 和 border-image-repeat 的简写属性。
border-image-source指定用作边框的图片的路径。
border-image-slice指定如何将源图片切片成区域。
border-image-width指定边框图片的宽度(厚度)。
border-image-outset指定边框图片区域超出边框盒(border box)的量。
border-image-repeat指定如何调整源图片的边缘区域(stretch、repeat、round、space)。

在 MDN 上探索交互式示例和详细信息:https://developer.mozilla.org/en-US/docs/Web/CSS/border-image