Tooltips in CSS
A tooltip is a small box that appear near an object in a graphical user interface when a pointer or other cursor controlled by a mouse passes over or rests on that object and which contains a brief text message identifying or explaining the object. In the context of a website the information shown in a tooltip is read from the title tags of an element on a page. These are stylized all over the web general using JavaScript and CSS. That’s not what I’m going to be teaching you to create though. I am going to show you how to write a tooltip in pure CSS.
Let’s start with a basic XHTML document.
<p> <a href="http://www.johndesu.com/" class="tooltip"> John Dyer<span> (Visit my blog) </span></a> is a student at the University of Pittsburgh majoring in computer science. </p>
Notice that the link has been given a class of tooltip. Inside my link I have added the text I want to be displayed as the link text and the text I want to be displayed in a tooltip. It is good practice to enclose the tooltip text in brackets like I have done so that it will still make sense if styles are turned off.
Now we need to set the position property of the anchor tag to relative in order to be able to position the contents of the span absolutely in relation to it’s parent element, the anchor tag. We also don’t want the tooltip text to display by default so we will set it’s display property to none.
a.tooltip { position: relative; } a.tooltip span { display: none; }
Next we want to make the text contained in the span tag appear when the anchor is hovered over. We do this by setting the display property of tooltip:hover span to block and positioning the contents of the span below and to the right of anchor using absolute positioning.
a.tooltip:hover span { display: block; position: absolute; top: 1em; left: 2em; }
And that’s really all there is to it. Let’s add some custom styling now to make it look more like a tooltip. Feel free to change any of stylistic settings to your liking. This is obviously just an example.
a.tooltip:hover span { display: block; position: absolute; top: 1em; left: 2em; border: 1px solid #996633; padding: 0.3em 0.5em; background-color: #FFFF66; color: #000; }
Note that this technique requires a standards compliant browser such as Firefox. Of course there are issues in IE and for some reason there can be problems in Safari as well. A quick fix for IE 5.x from Andy Budd is the following:
a.tooltip:hover { font-size: 100%; /* Fixes bug in IE5.x/Win */ }
If you enjoyed this tutorial, why not subscribe to my feed to receive the latest updates and tutorials from JohnDesu.