How do I add a gradient border to an image?

Sophia Bell
3 min readAug 2, 2021

--

A quick and simple way to add a gradient border to an image and how you can play around with it.

Photo by Gradienta on Unsplash

Adding a gradient border to your image couldn’t be simpler! Here are a few examples through the medium of cake batter.

All you have to do is set the background-image and padding of your image. The image size will be reduced on each side by the padding stated and in its place you will see the background gradient you have added:

This will display as follows:

By default, linear-gradient will go from top to bottom, but you can add in a variety of values to make the gradient go from left to right, bottom to top, at a 45 degree angle, etc. Check out MDN web docs for more examples.

The fun doesn’t stop there. What if you only wanted a partial gradient background, maybe just on one corner of the image?

Here we are padding out the bottom left hand corner, and positioning the background gradient to appear in that same corner. I’ve also decreased the size of the background image on both sides so the gradient appears to disappear half way along the image.

But that right hand corner is looking a little bare, so let’s add a gradient border up there too:

We’ve followed a very similar pattern to the previous example but specifying a right top border (as you can see from background-position). The main difference here is the use of auto for the width of the right hand background image. If we were to use 30px, as we have done for the others, the right hand gradient would disappear — or at least it would be there but hidden by the image. With auto, what is really happening is that the gradient is filling up the whole background from the left.

Remember, if you want the image to be a set size then you have to take into account the padding needed for the border.

And that’s it! Have a play around and let me know if you come up with any other ways to display a gradient image border.

--

--

Sophia Bell
Sophia Bell

Written by Sophia Bell

Software Engineer at Credera UK

No responses yet