Animated gradient border in CSS

Johnny Fekete
2 min readFeb 9, 2018

Learn how you can enhance your UI with this animated border. It’s perfect for highlighted content, it really stands out and pulls attention — and super easy to implement!

Get the code at https://codepen.io/johnnyfekete/pen/WMoWvb

CSS border properties don’t support background images, nor animation. However, by adding an :after pseudo-element and using `clip-path`, we can achieve the same effect as having the border.

All we need to do is to set the coordinates of the frame:

clip-path: polygon(0% 100%, 3px 100%, 3px 3px, 197px 3px, 197px 97px, 3px 97px, 3px 100%, 100% 100%, 100% 0%, 0% 0%);

In this example we had a 200x100px div with 3px frame.

Now we can apply gradient background that’s only showing up under this path, and not the whole div.

However, there’s a catch: clip-path needs to use a static size to calculate the frame’s inner coordinates on the right side and at the bottom.
That means we would need to know the width and height of the element that gets the animated border.

Thankfully, there’s a solution for this problem: the not-so-well-known calc() function (really, it deserves more attention, quite a handy function 💖 )

With that, we can let the browser do the calculation for us. It’s quite smart because you can use different measurements within one function, and it will return the correct value.

So calc(100% -3px) is perfectly correct, and if the width is 200px, it would return 197px.

It’s safe to use, even in older browsers, so play around with it.

Clip-path, on the other hand, is not supported by IE or Edge, so if you need to support them too, you need to provide some fallback solution. And when implementing it, don’t forget to add the necessary browser prefixes (-webkit-clip-path).

Update — 2023:
Since writing this article, I used this technique in many projects, including in my own startup—a product tour creator for web apps.

It works just as well, and with close to 100% browser support.

So grab the code, feel free to ask/comment below, and please give some claps if you found it useful.

One small clap for man, one giant leap for my blog. 🚀 Please help my article to reach others 👏👏👏

--

--

Johnny Fekete

trying to become a better person every day; making cool stuff for web and mobile; growing my business, bonboarding.com