Get "PHP 8 in a Nuthshell" (Now comes with PHP 8.3)
Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

Gradient-y Box Shadows in CSS

Okay… Here’s a confession. I love box shadows! And you can make it out by looking around on this blog. They are all over the place. Some are subtle while some are prominent.

I don’t know why but there’s something about shadows that appeals to me a lot and I always get tempted to use them wherever and whenever possible.

While the regular box-shadows are great, sometimes, you can spice them up by making them gradient-y because why not?

Let’s see how you can make one.

It isn’t the box-shadow

The first thing I want to clarify over here is this won’t be the box shadow that you make natively using the box-shadow property but rather a ::before pseudo-element trickery that disguise as a box shadow.

So, let’s say we have a simple div with a class box centered around in a container.

.box {
  height: 50%;
  width: 50%;
  background: bisque;
  aspect-ratio: 16/9;
  border-radius: 15px;
}

Here’s how it looks like.

See the Pen Box Without A Gradient Shadow by Amit Merchant (@amit_merchant) on CodePen.

The ::before pseudo element trickery

Now, if we want to add a gradient-y box shadow behind this box, we can do it using a ::before pseudo-element around it and makes it looks like a shadow.

.box::before {
  content: "";
  background: linear-gradient(90deg, purple, green, hotpink);
  position: absolute;
  height: 50%;
  width: 50%;
  z-index: -1;
  filter: blur(20px);
}

As you can tell, since we want a gradient shadow, we’re using linear-gradient as the background of the pseudo-element.

Next, by positioning the pseudo-element absolutely and keeping its width and height 50%, we are making sure that it stacks on top of the box.

And to position it behind the box, we used a negative z-index. That will do the trick for us.

And finally, to make the shadow natural, we made it blurred using a combination of the filter property and the blur() function.

You can adjust the amount of blur by increasing or decreasing the radius value for the blur() function.

The result

Here’s the entire example in action!

See the Pen Gradient Shadow by Amit Merchant (@amit_merchant) on CodePen.

If you want to change the angle of the shadow further, you can use top, bottom, left, and right properties accordingly.


Are you a visual learner? I have got you covered there as well!

Like this article? Consider leaving a

Tip

👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.

Comments?