how to add a gradient border in css

To add a gradient border to a box in CSS, you can use the following approach, which utilizes border-image or a pseudo-element to apply a gradient. Here’s how you can do it:

1. Using border-image:

.box {
    border: 4px solid transparent;
    border-image: linear-gradient(45deg, #ff6b6b, #f06595, #a29bfe);
    border-image-slice: 1;
}
In this method:
border: 5px solid transparent; defines the width of the border but makes it transparent so that the gradient can be applied.
border-image applies a gradient as the border.
border-image-slice: 1; ensures that the gradient stretches across the entire border.

Result:

2. Using a Pseudo-Element:

You can also use a pseudo-element (::before or ::after) for more complex designs like rounded corners or inset borders:
.box {
    position: relative;
    padding: 20px;
    background: white;
    border-radius: 8px;
}
.box::before {
    content: '';
    position: absolute;
    top: -4px; left: -4px; right: -4px; bottom: -4px;
    z-index: -1;
    background: linear-gradient(45deg, #ff6b6b, #f06595, #a29bfe);
    border-radius: 8px;
}

In this approach:

The ::before pseudo-element creates a layer behind the .box element with the gradient as its background.
By positioning it with top, left, right, and bottom, it surrounds the box with the gradient.
This allows for more customization, like rounded corners or inset borders.
Both methods give you a gradient border while keeping the inner box content intact.

Result:

Demo