
Unlike SVG strokes, CSS borders don’t accept gradient colors, but this doesn’t make them impossible to achieve. With many options available for creating this border effect, this article sheds light on the simplest one of them, so you can take your UIs to the next level with a touch of modernism.
Markup
For this method, a basic HTML structure with one element is needed:
<p class="gradient-border">Hello world</p>
Styling
The CSS for gradient borders works by layering two background images: one that extends into the border area - which will have the gradient, and the other covers the padding area.
First, we set the border
property to a transparent color, allowing the gradient background behind it to be visible,
.gradient-border {
border: 5px solid transparent;
}
Then for the background, we will draw two stacked layers separated by a comma, where the first layer will cover the last one, that’s why we will define the background color first, then the border gradient :
.gradient-border {
border: 5px solid transparent;
background: linear-gradient(white, white) padding-box,
linear-gradient(to right, #f38ca8, #fab387, #a8e2a1) border-box;
}
What makes this work is the second part after the image; the background-clip
, which defines the clipping area of the background.
We set the clipping to border-box
for the gradient to extend the border, and to padding-box
for the top layer to cover the gradient in the padding and content area.
We can’t specify a solid color (e.g., #fff) because this only works with images; so we use the same values twice inside linear-gradient()
to get a solid color for the background.
What makes this method effective is its support for border-radius, unlike the border-image
property.
Conclusion
Overall, gradient borders add their own flavor to a website, and we can take it one step further by animating the gradient with the help of the @property rule.