A while ago, I made this cool animated Multi-colour text effect in CSS.
I was re-looking this article and thought we could use some of these learnings to make a super cool animated border effect!
The end result for today will be this cool animated border gradient.
Setting up the basis for a gradient border
Gradient borders in CSS are tricky, as we need to leverage the border-image
property for this. It's not a super well know property and comes with some caveats.
However, let's give it a go.
We'll first make a single div in our HTML setup.
<div></div>
Let's give this div a big width and height so we can have a good demo.
div {
width: 50vmin;
height: 50vmin;
border: 1rem solid;
}
This will create a div that is half the width of our viewport. And give this div a 1rem
border.
The next thing we want to add is the actual border-image. We can pass an actual image or set SVGs or a gradient as this gets rendered as an image.
div {
width: 50vmin;
height: 50vmin;
border: 1rem solid;
border-image: linear-gradient(0deg, #12c2e9, #c471ed, #f64f59) 1;
}
We should now have our basic border setup, and it should look like this.
Pretty close already. Now we just need to animate this!
Let's use some CSS variables to make the position animatable.
div {
--angle: 0deg;
width: 50vmin;
height: 50vmin;
border: 1rem solid;
border-image: linear-gradient(var(--angle), #12c2e9, #c471ed, #f64f59) 1;
}
This introduces a new --angle
variable. This is nothing that CSS knows about but our own variable.
We can then add a basic animation query as well.
animation: 5s rotate linear infinite;
And the rotate animation will look like this:
@keyframes rotate {
to {
--angle: 360deg;
}
}
However, nothing will happen!
The value will change, but since it's not a know CSS variable, we need to define it as a changeable property.
@property --angle {
syntax: '<angle>';
initial-value: 0deg;
inherits: false;
}
And now we got our working animated border in CSS!
Browser Support
For browser support, we have to technically look at multiple properties. Still, this one below should give you an excellent example of how good the support is.
Thank you for reading, and let's connect!
Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter
Top comments (7)
The support of border-image is good but the one of @property is not. This won't work on firefox yet. Only Chromium browser support this (Edge, Chrome)
Yeah correct, bit of a pity it's not supported yet.
You can enable it as a setting
This looks good. I have an animated border in my obs setup by having a moving gradient webm file behind it.
Oh nice! That's pretty sick
Inspired by the 30s of pokiemane I watched. She has a sick setup.
Reading this in Safari, not animated.
Correct @property is only chromium for now :(