CSS 9 Slice Technique

csshtml

Understanding 9-slice scaling

9-slice (aka 9-patch) is a technique for scaling images and UI assets so corners stay crisp while edges and the center stretch or tile. This short guide shows the concept, an annotated diagram, and small examples you can try.

What is 9-slice scaling?

9-slice scaling is a method for resizing images—especially UI elements—so that the corners remain unscaled, the edges stretch or tile, and the center fills the remaining space. This technique is widely used in UI design to keep borders and corners sharp regardless of the element's size. For a deeper background, see Wikipedia: 9-slice scaling.

How to achieve 9-slice with CSS

In CSS, the border-image and border-image-slice properties let you apply the 9-slice technique to any element. You provide an image, define how to slice it into a 3x3 grid, and control how each region is stretched or repeated. This is especially useful for scalable buttons, panels, and decorative frames.
See: CSS-Tricks: border-image-slice and GeeksforGeeks: How to slice image specified by border-image-source in CSS.

Code Example Breakdown

border-image: url(/images/9slice.jpg) 40 42 37 39 fill / 40px 42px 37px 39px;
  • url(/images/9slice.jpg): The image to use for the border.
  • 40 42 37 39: The border-image-slice values (top, right, bottom, left). These numbers define how far from each edge the image is sliced, creating the 9 regions.
  • fill: Fills the center area with the image (not just the border).
  • / 40px 42px 37px 39px: The border-width for each side (top, right, bottom, left). This controls how much space the border image occupies.

The result: corners are preserved, edges stretch, and the center can be filled, allowing for flexible, scalable UI elements with crisp borders.

Try it interactively

Want to experiment with your own images and slice values? Try the Leanrada 9-slicer tool to visually adjust and preview 9-slice settings in real time.

Example of 9 slice strech

Drag bottom right corner

Example of 9 slice repeat

Drag bottom right corner

/* Example: use a PNG as a border-image */
.nine-slice {
  aspect-ratio: 1 / 1;
  max-width: fit-content;
  border-image: url(/images/9slice.jpg) 40 42 37 39 fill / 40px 42px 37px 39px;
  padding: 40px 42px 37px 39px;
}
/* uses repeat and background color */
.nine-slice-repeat {
  resize: both;
  overflow: auto;
  max-width: 500px;
  max-height: 500px;
  aspect-ratio: 1 / 1;
  max-width: fit-content;
  border-image-source: url(/images/9slice.jpg);
  border-image-slice: 40 42 37 39;
  border-image-width: 35px 42px 37px 39px;
  border-image-outset: 0;
  border-image-repeat: repeat;
  padding: 40px 42px 37px 39px;
  background-color: white;
}