Monday, 5 March 2012

CSS: simple tooltips

   


When navigating a web page, the user sometimes needs some help on words, links, images, or any other element displayed. Tooltips can be very useful, and I've already published a post about them.

While the mentioned article is explaining a jQuery solution, in the following example we are going to use just plain HTML and some CSS rules.

It will be a simple and straightforward solution, but an effective and efficient one as well.

Let's see how we can do it.


The HTML
We need to insert a sample text with a link inside which will show an helping tooltip.
<div>
This is a simple <a href="#" class="toolTip">tooltip<span>A message that appears when a cursor is positioned over an icon, image, hyperlink, or other element in a graphical user interface.</span></a> made only with HTML & CSS.
</div>
The above snippet is quite easy to understand.
It has a span containing the definition of "tooltip". The span will be shown only on hover. Basically we need to apply some CSS rules, in order to hide the span and make it visible when needed. We will apply some other styles in order to make the user aware of that possibility.

The CSS
We can style the main container (div tag), but it's not really necessary, as you may understand:
div
{
    font-size: 13px;
    font-family: verdana;
}
Afterward, we apply a rule to the link:
a.toolTip
{
    color: #000000;
    text-decoration: none;
    cursor: help;
    border-bottom: dashed 1px #000000;
}
As an embelishment, we have styled the link with a dashed bottom border, in order to inform the user that there's something going on with the "tooltip" word.
Now, we make the span (containing the tooltip definition) invisible:
a.toolTip span
{
    display: none;
}
And then we style it, on hover:
a.toolTip:hover span
{
    display: block;
    position: absolute;
    top: 20px;
    left: 30px;
    background: #EEEEEE;
    font-style: italic;
    padding: 5px 5px 5px 5px;
    border: solid 1px #DDDDDD;
    width: 300px;
}
a.toolTip:hover
{
    position: relative;
}
The only notable thing in the above snippet is the width of the span: we need to find an appropriate width for the element, so that the definition will be completely displayed.

And that is all.
I hope you've found the above example useful.

2 comments:

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.