How to create a simple tooltip using only CSS3

This article demonstrates how to create a simple tooltip using only CSS3 with minimal styles. Consider the following example of tooltips for links.
Tooltip is a box with additional information which appears near the element when user hovers the cursor over the element. Tooltips are often used to provide captions for images or descriptions for links. Using them is a good way to provide more information for the user without cluttering the content on the page.
HTML code
<a href="#" data-tooltip-text="Tooltip text" class="tooltip">Just simple text</a>
As can be seen in the code above, the link requires two things:
- class "tooltip" which is used to apply tooltip styles;
- data-tooltip-text attribute whose value is used as content for tooltip box.
CSS code
The following styles are used to display links with class "tooltip" as inline elements using relative positioning.
.tooltip { display: inline; position: relative; }
Next styles are used to create a tooltip box with rounded corners which contains the content of the current tooltip and position it above the link:
.tooltip:hover:after { background-color: #000000; /* for old browsers */ background-color: rgba(0, 0, 0, 0.85); -webkit-border-radius: 8px; -moz-border-radius: 8px; border-radius: 8px; bottom: 26px; color: #FFFFFF; content: attr(data-tooltip-text); left: 20%; padding: 5px 10px; position: absolute; width: 190px; z-index: 1000; }
The style above use hover pseudo-class and after pseudo-element, the first one shows a tooltip box with its content which is inserted by the second one after the selected element (the link with class "tooltip" in this case). Also in the styles RGBA color is used to make tooltip box 85% semi-transparent. Rounded corners for tooltip box are achieved by border-radius CSS property.
The most important thing in the style above is content: attr(data-tooltip-text);
which takes value of data-tooltip-text attribute in the current link with class "tooltip" and inserts this value in tooltip box as its content.
The following styles add an arrow and position it in the bottom of the tooltip box.
.tooltip:hover:before { border: solid; border-color: rgba(0, 0, 0, 0.85) transparent; border-width: 8px 8px 0 8px; bottom: 18px; content: ""; left: 50%; position: absolute; z-index: 1001; }
In the styles above a hack with border CSS properties is used to create a pseudo arrow. It sets border colors to transparent for the left and right sides of the block with appropriate border widths.