DEV Community

Paul
Paul

Posted on

3 1

Speech bubbles with background images

I wrote this post a few years ago, but I'm dragging it back into the light kicking and screaming because of another speech bubble-type post that I came across recently.

I wanted to have a speech bubble-like element with a custom background image. This method is pretty hacky, but it works and it doesn't have limited browser support, unlike clip-path.

The typical way to do this is simple — use the container's :before or :after pseudo-element to create a CSS triangle, and attach it to the appropriate edge.

Like so:

You see the problem, don't you? The arrow is dangling off the edge of the bubble, sure enough, but it looks woefully out of place with its solid color. It can look much nicer than that with some trickery.

The typical speech bubble arrow effect is created by adding an element; in our previous example, a single pseudo-element with a border hack.

What we're going to do is also a border hack. But instead of adding an element, we're going to create the illusion of taking something away.

The containing element and the content wrapper are the same as in the first example. But the background isn't full width; we're going to pull it farther out — ten pixels for this example, but you want to pull it out exactly the width of your arrow.

The trick here is to use the background element's :before and :after pseudo-elements to overlay that extended area. We're essentially going to carve out the shape of our arrow.

Here is an example with different colors for each of the borders, which allows you to see the shape we're going to make.

We'll make the left, top, and bottom border colors transparent, creating the outline of the arrow, and the right border will need to match the background of the element containing the speech bubble. That's important, or the effect is lost.

So here is the final result:


This was originally published on my blog.

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Cloudinary image

Optimize, customize, deliver, manage and analyze your images.

Remove background in all your web images at the same time, use outpainting to expand images with matching content, remove objects via open-set object detection and fill, recolor, crop, resize... Discover these and hundreds more ways to manage your web images and videos on a scale.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay