Speech Bubble in Pure CSS

June 2, 2012
Not so long ago, I have discovered two new CSS3 pseudo elements - :before and :after (They are actually CSS2 features, but lets discuss it in the context of CSS3). I have read about them long ago but was uninterested due to lack of practical use until recently I came across this blog post by Nicolas Gallagher, where he shows how to use them to create a speech bubble.
The beauty of this approach is that ANY DIV can look like a speech bubble WITHOUT the use of any additional SUPPORTING ELEMENTS. The CSS is simple so is HTML. Here is the CSS: Here is the HTML: Here is the result:

Simon Says:
Turn left and clap 3 times

How it works

You can create various speech bubbles and put text of any length. You can also overlay this bubbles on top of other elements if you make position absolute. I have found it useful in form validation. I display an error messages after the field that has an error. Here are some more examples:
Multiline tooltip
Has two lines
Multiline tooltip
Has two lines
Multiline tooltip
Has two lines
Multiline tooltip
Has two lines
To achieve the corner effect, is uses border trick. What will happen if you define a border for TOP as a 5px solid line and border for LEFT and RIGHT as 5px but transparent? Exactly! it will create a nice triangular shape.
It needs to be noted that if you want to keep the bubble expandable you can only put corner in 4 places: left-top, left-bottom or top-left, bottom-left. I did not figure out a pure CSS solution how to make it in other corners and still have it resized based on the amount of text inside. Here is entires CSS for this

A Background Color Problem and Solution

One of the problems with this approach is that you will not be able to create a bubble with a background different from the border color. This problem is inherit with the approach when you create a triangle based on border width. The article I mentioned above has a solution to this, but it was not very pretty, it used arbitrary margin and padding, which makes it content depended. If you add more content into your bubble, it will not work correctly.
I've found a much better solution, but it uses CSS3 property. All you need to do is to turn the :before or :after element. Here are a few examples:
Multiline tooltip
Has two lines
Multiline tooltip
Has two lines
Multiline tooltip
Has two lines
Multiline tooltip
Has two lines
Here is HTML Here is CSS The last example uses inherit property to read background color and border color if you decide to change it in inline style.

User Comments

Other Articles