Archive for the ‘CSS3 Tutorials’ Category

Creating A CSS Speech Bubble

You’d be surprised how many things you can do with some relatively simple CSS. Even more surprising are the applications of some of the CSS pseudo classes, in particular :before and :after. These pseudo classes might seem foreign because they aren’t very commonly used, but in reality they are quite simple. They are used to add content (before or after, duh!) the class they are applied to. They essentially inject an element that you can then apply additional CSS to. So the speech bubble example below is created using just a div and both pseudo classes.

“This could be a quotation from a customer or use it in an HTML cartoon you've created.

The possibilities are endless!”

Here’s the HTML:

<div class="bubble">
<p>"This could be a quotation from a customer or use it in an HTML cartoon you've created.<br /><br />The possibilities are endless!"</p>

The CSS is pretty simple, which is good to go along with a very simple piece of HTML. The :after pseudo class creates the blue point, and the :before class creates a smaller white point that makes the blue just look like an outline. The points are actually made using two thick borders on only two sides of a block element that actually has no width or height. It was hard for me to grasp how borders create a filled element when I first saw this, but if you just play with the border widths, you’ll get the hang of it.

Here’s the CSS:

div.bubble {
  display: block;
  margin: 0 auto 40px auto;
  width: 250px;
  background-color: White;
  border: solid 6px #143463;
  border-radius: 20px;
  text-align: center;
  position: relative;
div.bubble p {
  margin: 10px;
  font-size: 11px;
  color: #143463;
div.bubble:before, div.bubble:after {
  border-color: White transparent transparent transparent;
  border-style: solid;
  border-width: 20px 0px 0px 40px;
  content: &quot;&quot;;
  display: block;
  height: 0;
  width: 0;
  line-height: 0;
  position: absolute;
  z-index: 5;
  bottom: -20px;
  left: 150px;
div.bubble:after {
  border-color: #143463 transparent transparent transparent;
  border-style: solid;
  border-width: 24px 0px 0px 48px;
  content: &quot;&quot;;
  z-index: 4;
  bottom: -30px;
  left: 148px;

And that’s it! In my next post, I’ll discuss how to use this speech bubble concept to create a JQuery Tooltip. Any questions? Ask away!