Saturday, January 7, 2012

Tooltip on Hovering Links

We can use CSS alone to display tooltip when we hover on links. The idea is that we'll add a span tag to the anchor text and hide them initially using display: none; for the span tag. Only when we hover, we'll display the span tag by changing display to block.
Say I need to show tooltip "..lost in silence" when I hover on a link with text 'kadaj'. Then the anchor tag will be
<a id="t1" href="">kadaj<span>..lost in silence</span></a>
and the CSS for that is
/* hide span tag in the anchor tag (which is our tooltip) */
#t1 span {
display: none;

/* on hover show the span tag (tooltip) */
#t1:hover span {
display: block;
position: absolute;
top: 11em; /* depends on the position of the link */
left: 6em; /* depends on the position of the link */
border-radius: 3px;
text-align: center;
font: 10px Verdana, sans-serif;
padding: 0 .5em 1.5em .5em;
margin: .5em;
width: 13em;
z-index: 100; /* to show on top of other elements */
border:1px solid darkcyan;
background-color: lightcyan;
opacity: .9;
color: black;

/* styling tooltip image */
#t1:hover span img {
position: relative;
top: .7em;
left: .2em;
z-index: 100;
The only thing that changes is the top and left value depending on where the tooltip should appear when you hover on the link. However, there is a drawback when using this method. It will work only if the position of the link is fixed. Here we are using absolute position for the tooltip, so if the position of the link changes, the position of the tooltip won't change, unless you use javascript and change it accordingly. It is good for pages with fixed layout. Not ideal for blog posts, where the position of the post changes when new posts appear.