DEV Community

Cover image for A nifty alternative to box-shadows
codestruct.io
codestruct.io

Posted on

A nifty alternative to box-shadows

Most folks know about the box-shadow property and use it a lot already in their CSS, however there are certain scenarios where a box-shadow doesn't give us ideal results. There is however also a CSS filter called drop-shadow that let's us do some cool things we cannot achieve with box-shadows. It's currently supported in all modern browsers and definitely worth a look. Here's how a drop-shadow looks like in CSS:



.selector {
  filter: drop-shadow(0 10px 12px rgba(0, 0, 0, 0.4));
}


Enter fullscreen mode Exit fullscreen mode

What's the use case?

While box-shadows are sufficient in most scenarios, they can only give us a shadow around the exact shape of an element, which is usually angular or round due to a border-radius. With drop-shadows however, we can cast a shadow around elements and even images that stays in direct proximity to the non-transparent parts of the image or element.

So in essence this works on regular HTML elements, SVGs and also transparent PNGs. Here's an example:



.triangle {
    width: 180px;
    height: 180px;
    background: linear-gradient(45deg, yellow 50%, transparent 50%);
    filter: drop-shadow(0.2rem 0.2rem 1rem rgba(0,0,0, 0.8));
}


Enter fullscreen mode Exit fullscreen mode

Alt Text

One downside we can spot in the syntax here is that we're not able to set a spread parameter the shadow should have. Other than that, the parameters match what we're used to with box-shadows (x-offset, y-offset, blur, color).

The real magic however becomes more obvious when we apply a drop-shadow to a transparent PNG, which gives us the same effect as seen above, instead of just putting a shadow on the whole image or container, we see the shadow aligned to the filled lines and shapes.



<style>
    img {
        filter: drop-shadow(0.5rem 0.5rem 0.5rem rgba(0, 100, 200, 0.7));
    }
</style>
<img src="./waves.png">


Enter fullscreen mode Exit fullscreen mode

Alt Text

Stay tuned for more frontend-focused articles like this πŸ‘‰ https://allround.io

Top comments (0)