Skip to main content

How to make gradient borders in CSS

· 3 min read
;

Introduction

CSS border attributes allow you to set the border style, width, and color of an element.

  1. Using the border-image property

The most basic way to apply a gradient to a border is to utilize the border-image property (similar to how background gradients are applied):

.gradiantBorderOne {
border: 15px solid;
border-image-slice: 1;
border-width: 5px;
border-image-source: linear-gradient(to left, #00c853, #b2ff59);
}
  • The '1' following the linear-gradient statement represents the border-image-slice value. We designate a single border region by using the number 1.
caution

The disadvantage of this technique is that border-image and border-radius cannot be combined ⛔, This means that border-radius property will not work.

  1. Using the pseudo selector

.gradient-box {
display: flex;
align-items: center;
//width: 50vw;
width: 90%;
margin: auto;
max-width: 22em;

position: relative;
padding: 30% 2em;
box-sizing: border-box;

$border: 5px;
color: #fff;
background: #000;
background-clip: padding-box; /* !importanté */
border: solid $border transparent; /* !importanté */
border-radius: 1em;

&:before {
content: "";
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: -1;
margin: -$border; /* !importanté */
border-radius: inherit; /* !importanté */
background: linear-gradient(to right, red, orange);
}
}
  1. Using the background-clip approach

There is an alternate solution that is consistent with the border-radius property and is based on the background-clip property.

.gradientBorderTwo {
background: linear-gradient(white, white) padding-box, linear-gradient(
to right,
red,
cyan
) border-box;
border-radius: 20%;
border: 3px solid transparent;
}
  • The background-clip values are represented by the 'padding-box' and 'border-box' values supplied after the linear gradients.

The initial linear gradient is restricted to the padding box (i.e., all the content of the element, except the borders). Because we're using the same color twice, it's a 'fake' gradient; we're using it to mask the second background gradient with the background color.

The second gradient is placed beneath the first and is used to apply the gradient colors. The second gradient, in contrast to the first, encompasses the border region (background-clip: border-box).

Finally, a translucent border is needed to distinguish the border-box from the padding box (otherwise they would be identical and the first gradient would completely cover the second one).

Conclusion

Thank you for coming this far with me today; I hope it was useful to you, and I hope to see you again in future techniques and courses.

Happy coding 🎉