Using SVG as a Border with CSS
Jack Harner 🚀
Posted on August 7, 2018
Have you ever wanted a cooler border than what you can get from stacking border
elements? Well fear not, today I'm going to walk you through the border-image
CSS property.
Here's the image we are going to chop up into a border:
Download it Here if you're following along.
This works with raster images as well, but due to scaling issues it's best to use SVG.
Border-Image
Bare minimum you need to set the border
which sets the width of the border image (and acts as a fallback, although browser support is Pretty Good) and the border-image
property.
.border{
border:20px solid;
border-image:url(border.svg);
}
Obviously, while interesting, this isn't the intended result, so we have a few more steps.
Border-Image-Slice
The border-image-slice property tells the browser where to cut the image to create the different edges. It accepts up to 4 either unitless numbers, or percentages.
The values measure from the top, right, bottom, and left edges of the image (in that order). If one of the units is missing it will mirror the other side.
// These are all the same.
border-image-slice: 0 40;
border-image-slice: 0 40 0 40;
border-image-slice: 0 40 0;
So, back to our example, since the image we're using is symetrical it makes it easy to slice:
.border{
...
border-image-slice:170;
}
Ta Da!! You have a custom image border. There are a couple other border-image
properties that can affect how the border reacts to scaling and other things. Check out this article from CSS-Tricks which goes into a little more detail about all of this.
Use Case
Nobody wants a squiggly line on their borders but this is what I was working on when I learned about border images.
The frame and the chalk are part of the SVG image making up the border. This allows the container to retain the look of a chalkboard, regardless of what layout or size the content inside is.
Do you see yourself using this ever? Why or why not?
Posted on August 7, 2018
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.