Gradient Borders in CSS

Avatar of Chris Coyier
Chris Coyier on (Updated on )

Let’s say you need a gradient border around an element. My mind goes like this:

  • There is no simple obvious CSS API for this.
  • I’ll just make a wrapper element with a linear-gradient background, then an inner element will block out most of that background, except a thin line of padding around it.

Perhaps like this:

If you hate the idea of a wrapping element, you could use a pseudo-element, as long as a negative z-index value is OK (it wouldn’t be if there was much nesting going on with parent elements with their own backgrounds).

Here’s a Stephen Shaw example of that, tackling border-radius in the process:

You could even place individual sides as skinny pseudo-element rectangles if you didn’t need all four sides.

But don’t totally forget about border-image, perhaps the most obtuse CSS property of all time. You can use it to get gradient borders even on individual sides:

Using both border-image and border-image-slice is probably the easiest possible syntax for a gradient border, it’s just incompatible with border-radius, unfortunately.

DigitialOcean documents the same approach in another tutorial.