Using a Gradient as the Image in a CSS Border-Image
The CSS border-image
property accepts any valid image format for its image value. That includes CSS gradients. I regularly get design comps that include border gradients (usually a solid line that fades to transparent at both ends). Combining gradients with border-images allows me to do that without needing an image / pseudo-element hack. Here’s a pen:
See the Pen Using a gradient for a border by James Steinbach (@jdsteinbach) on CodePen.
I’m using Sass with Bourbon’s border-image @mixin to handle cross-browser prefixing. After the gradient syntax, I used 1
for all the slice values – this tells the browser where to offset any slice in the image (which we’re not doing). The stretch
value sets the gradient to 100% width & height of the border-box. After the border-image declaration, I fine-tuned the actual width with the border-width
property, including a :last-child
to remove the extra border from the final item. (You can read all the juicy details about the CSS border-image property on CSS-Tricks.)
Using CSS gradients for border-images gives us a lot more customizability than simple solid (dashed, double, whatever) borders. For example, you could use this on an <hr />
element or the bottom of any element to get a fade-in-out line for a divider between vertically stacked elements. You could also use a radial gradient to create more interesting picture borders. Check this pen out:
See the Pen Using a radial gradient for a border by James Steinbach (@jdsteinbach) on CodePen.
Of course, there’s a big IE catch: border-image is only supported by IE11. If this ornamentation is necessary, you’ll want to include a solid border-color fall-back for IE10 & down.
What uses do you see for using CSS gradients as the image in a CSS border-image property? Please share a CodePen, JSFiddle, Dabbblet, SassMeister gist, (or whatever sandbox you prefer!) in the comments below!