Tooltips are a great way to show your user more information by simply hovering over an image or text. They can be used, for example, to provide captions for images, or longer descriptions for links, or any useful information which would improve the user experience of your site, without intruding on the design.
Today I’m going to show you how to create a simple tooltip using HTML and CSS to display the title tag of your hyperlinks.
Let’s start off by creating some simple markup for the link. We need to give it a title which will be the tooltip content, and assign it a class:
<atitle="This is some information for our tooltip."class="tooltip">CSS3 Tooltip</a>
The next step is to create some rudimentary styling for our tooltip class:
display: inline;position: relative;}
We are now displaying our tooltip inline with our link using relative positioning. Next we want to create the a rounded box to form the body of the tooltip, and position it so that it floats above the link:
We are using the :hover selector which selects an element, in this case our link, on mouseover and the :after selector, which inserts content after the selected element. We have specified a black background with 80% opacity, and for browsers that do not support RGBA colors we have provided a dark grey background.
Slightly rounded corners are created by using the border-radius attribute and we have set the text color to white. Lastly, we have positioned the tooltip box from the left of the link and added a little padding.
As well as the styling and positioning, we have set the content property:
This property allows us to insert the content we want which can be a string, a media file or an attribute of the element. In this case we are using the title attribute of the link.
Now when you hover over your link a tooltip should be appear above it with the text you set as your link title. We have one problem though, the title information is being shown twice: once in the tooltip and once by the browser. To fix this we need to make a slight change to our HTML:
<ahref="#"title="This is some information for our tooltip."><spantitle="More">CSS3 Tooltip</span></a>
What we’ve done here is is wrap the link text in a span tag with its own title attribute. Now the browser will display the title set in the span tag when the link is hovered over.
To finish we will add an arrow to the bottom of the tooltip, to give it that little extra touch of style. We do this by using the :before selector and some border styles:
We are using a few border hacks here to create the effect of an arrow: setting the border colors on the left and right to transparent and controlling the border widths. We’ve also positioned the arrow so it sits on the bottom of the tooltip box.
And there you have it, a simple tooltip with the title tag of the element hovered over. You could also use this for image alt tags, or even just put your own text into the CSS to pop up where you want.