How to Create Gradient Border in CSS: Simple Steps
To create a gradient border in CSS, use
border-image with a linear-gradient or radial-gradient. Alternatively, use background with padding and background-clip to simulate a gradient border effect.Syntax
The main way to create a gradient border is using the border-image property combined with a gradient function like linear-gradient. You set the gradient as the border image and define how it slices.
border-image-source: The gradient to use as the border.border-image-slice: Defines how the image is sliced to fit the border.border-width: Sets the thickness of the border.
Example syntax:
css
border: 5px solid transparent; border-image: linear-gradient(to right, red, blue) 1;
Example
This example shows a box with a 5px gradient border from red to blue using border-image. The inside is white and the border smoothly transitions colors.
css
div {
width: 200px;
height: 100px;
border: 5px solid transparent;
border-image: linear-gradient(to right, red, blue) 1;
background-color: white;
border-radius: 8px;
}Output
A white rectangular box with rounded corners and a smooth horizontal gradient border from red on the left to blue on the right.
Common Pitfalls
Common mistakes when creating gradient borders include:
- Not setting
border-styleor usingborder-style: none, which makes the border invisible. - Forgetting to set
border-width, so the border does not show. - Using
border-image-sliceincorrectly, which can distort the gradient. - Trying to apply gradient directly to
border-color, which does not support gradients.
Here is a wrong and right example:
css
/* Wrong: gradient on border-color (no effect) */ div { border: 5px solid; border-color: linear-gradient(to right, red, blue); } /* Right: use border-image with gradient */ div { border: 5px solid transparent; border-image: linear-gradient(to right, red, blue) 1; }
Quick Reference
Tips for gradient borders in CSS:
- Use
border-imagewith gradients for clean borders. - Set
border-styletosolidandborder-widthto see the border. - Use
border-radiusfor rounded corners with gradient borders. - Alternatively, use
backgroundwithpaddingandbackground-clipfor more complex shapes.
Key Takeaways
Use border-image with a gradient and border-width to create gradient borders.
Always set border-style to solid and border-width to make the border visible.
border-color does not support gradients, so use border-image instead.
border-image-slice should be set to 1 to properly display the gradient.
For rounded corners, combine border-radius with gradient border styles.