EN
CSS - gradient border
3
points
In this article, we would like to show you how to create gradient border for HTML elements using CSS.
Quick solution:
.element-border {
padding: 0.25rem; /* sets border width */
background: linear-gradient(to right, lightgreen, green); /* sets border color */
}
.element-content {
background: white; /* sets background color */
}
Note:
There's no such thing as gradient border in CSS.
In this solution, we use simple trick - create wrapper (
element-border
) element with gradient background withelement-content
element inside it. Theelement-content
element blocks out most of theelement-border
background, leaving a thin line ofpadding
around it.
Practical example
In this example, we create gradient background for HTML element.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
.element-border {
padding: 10px; /* sets border width */
background: linear-gradient(to right, lightgreen, green); /* sets border color */
}
.element-content {
padding: 10px;
background: white; /* sets background color */
}
</style>
</head>
<body>
<div class="element-border">
<div class="element-content">Some content here ...</div>
</div>
</body>
</html>
Alternative solution
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
.gradient-border {
--border-width: 10px; /* <------------ required */
padding: 10px;
margin: var(--border-width); /* <------------ required */
position: relative; /* <------------ required */
background: white; /* <------------ required */
}
.gradient-border:after {
position: absolute; /* <------------ required */
left: calc(-1 * var(--border-width)); /* <------------ required */
top: calc(-1 * var(--border-width)); /* <------------ required */
right: calc(-1 * var(--border-width)); /* <------------ required */
bottom: calc(-1 * var(--border-width)); /* <------------ required */
background: linear-gradient(to right, lightgreen, green); /* <------------ required */
content: ''; /* <------------ required */
z-index: -1; /* <------------ required */
}
</style>
</head>
<body style="padding: 5px">
<div class="gradient-border">Some content here ...</div>
</body>
</html>