Speech Bubble Arrows that Inherit Parent Color

Avatar of Chris Coyier
Chris Coyier on

📣 Freelancers, Developers, and Part-Time Agency Owners: Kickstart Your Own Digital Agency with UACADEMY Launch by UGURUS 📣

Interesting question:


By “css3 speech bubble”, Jin means using a pseudo element on a container to add a little pointer arrow (triangle). Not really CSS3, but that’s pedantic.

Let’s say that pink color isn’t practical to set in an external CSS file. Perhaps is a user setting, or perhaps its set dynamically somehow.

<div class="speech-bubble" style="background: pink;">
   I like bananas, because they have no bones.
</div>

Setting the container with an inline style is all well and good, but unfortunately there is no inline style for pseudo elements. So we might end up with something like this:

Bummer.

There is a solution though! While we are setting the inline style for the container, we can set an inline style for border-color too. Even though the container actually has no border, we can rely on inheritance to pass that color down to the pseudo element, which is treated like a child element.

<div class="speech-bubble" style="border-color: pink; background: pink;">
   I like bananas, because they have no bones.
</div>

Then in our code for the pseudo element, we’ll specifically have it inherit the color:

.speech-bubble:after {
   content: "";
   position: absolute;
   top: 100%;
   left: 20px;
   border-top: 20px solid black;
   border-top-color: inherit; 
   border-left: 20px solid transparent;
   border-right: 20px solid transparent; 
}

Notice that I’ve applied inherit to border-top-color rather than the shorthand property border-top. For some reason (feel free to enlighten me) inherit doesn’t work in the shorthand. Also note that when you override the the color with inherit, it doesn’t “inherit” from the color set just above it (black), it inherits from its parent. So if you need a default, you’ll need to set the border-color on the parent.

View Demo