Published:

Create Irregular Borders Using filter.

A feed I follow for design inspiration recently featured a website called The Outline. One element I really loved about it were these nifty, outlined images sprinkled throughout:

The Outline

In my never-ending quest to rid image editing software from my workflow as much as possible, I wondered to myself, “Is there a way we can achieve this effect in the browser?”

As it turns out, yes we can!

Go ahead and see for yourself—use your dev tools on this goofy guy’s face below to check it out:

Me
img {
  filter: drop-shadow(-0.125rem -0.125rem 0 #fff)
          drop-shadow(0.125rem -0.125rem 0 #fff)
          drop-shadow(-0.125rem 0.125rem 0 #fff)
          drop-shadow(0.125rem 0.125rem 0 #fff)
          drop-shadow(0.75rem 0.75rem 2px rgba(0, 0, 0, 0.5));
}

What exaclty is going on here (other than black magic)? According to MDN’s page on CSS filters, the drop-shadow() function creates a blurred, offset version of the input image’s alpha mask drawn in a specified color and composited below the image.

There’s no way to do a spread like we can with box shadows (womp womp), which is why we have to string multiple outputs together to achieve our desired result. The first four uses of drop-shadow() above are positioned towards the corners of the image and aren’t blurred, which work together to form the complete “border.” The fifth value gives us our actual shadow to round out the desired look.

Bonus content: I’m using a few additional filters such as grayscale(), brightness(), and contrast() to further adjust the appearance of the image. 👋 See ya later, Photoshop!

Building a Better Shadow

The implications of this are really exciting as drop shadows take the “computed shape” of an element into account, whereas box shadows simply respect said element’s box model. This means that in addition to ignoring transparency in images (like above), it can also follow the edges of any child element overflowing the parent, including :before or :after pseudo-elements. The difference can be subtle at times, but you can see it when comparing the following tooltips:

Hey!
Hey!
Hey!
Hey!
Hey!
Hey!

Notice how the shadows of the tooltips on the left don’t respect the outline of the caret at the bottom but the tooltips on the right do.

Thank you drop-shadow(), you make my OCD heart happy.