Today, I wanted to show you how you can use gradients for borders in CSS something that historically required faux borders and background colors, but is now supported natively.
The border at the top of the page #
My website typically has a gray border at the top…
body {
border-top: 0.5em solid #808080;
}
In years past, this effect has required hiding the border, and then adding a <div> element with a gradient background color…
<div class="border"></div>
.border {
background: #808080;
background: linear-gradient(
to right,
#ffafc7 10%,
#73d7ee 10% 20%,
#613915 20% 30%,
#000000 30% 40%,
#e50000 40% 50%,
#ff8d00 50% 60%,
#ffee00 60% 70%,
#028121 70% 80%,
#004cff 80% 90%,
#760088 90%
);
height: 0.5em;
}
Here, I’m defining a linear-gradient() that goes to the right. I like the to format better than degrees. I find it more human-readable.
Then, I define each of the 10 colors in the flag.
The numbers after each color are stops. They define where the color should start and stop along the gradient. By having each color start where the previous one left off, I end up with hard lines and no colors bleeding together.
If I omit the percentages, the colors blend together evenly across the gradient.
.border-blend {
background: #808080;
background: linear-gradient(
to right,
#ffafc7,
#73d7ee,
#613915,
#000000,
#e50000,
#ff8d00,
#ffee00,
#028121,
#004cff,
#760088,
);
height: 0.5em;
}
Using gradients for borders #
With modern CSS, you can now apply gradients to borders using the border-image property.
body {
border-top: 0.5em solid #808080;
}
I can take the background gradient we used in the previous example and apply it as the value of the border-image property instead.
body.border-lgbtq {
--border-color: linear-gradient(
to right,
#ffafc7 10%,
#73d7ee 10% 20%,
#613915 20% 30%,
#000000 30% 40%,
#e50000 40% 50%,
#ff8d00 50% 60%,
#ffee00 60% 70%,
#028121 70% 80%,
#004cff 80% 90%,
#760088 90%
);
border-image: var(--border-color) 1;
}
This is a shorthand property, and also requires a border-image-slice value of 1.
Here’s demo Gradient with CSS
🐘 Is the best way to help create Gradient borders with CSS,...
If you enjoyed this article, you may also like Dervic Blog's.
Comments (0)