Thursday 10 Jan 2008

CSS tooltips

Let's begin with something simple, make customizable tooltips appear, without using Javascript but only the :hover CSS pseudo-class.

First we write the HTML, with links that need an additional information which will be visible only when the mouse is over the links. (This is possible with anything else that links, but then this won't work in IE <7.)

<ul class="links">
  <li><a href="#">My 1st link<span>This is my 1st link description.</span></a></li>
  <li><a href="#">My 2d link<span>This is my 2d link description.</span></a></li>
  <li><a href="#">My 3rd link<span>This is my 3rd link description.</span></a></li>
  <li><a href="#">My 4th link<span>This is my 4th link description.</span></a></li>

From the CSS file, we will start to stylize the descriptions in the span inside the links. This will be easier to tweak them before, then hide them after:

ul.links a span
  position: absolute;
  left: 30ex;
  background-color: #ffd;
  /* Yellow color close to a real help tooltip. */
  font-size: small;
  text-decoration: none;
  width: 25ex;
  padding: 3px;
  border: 1px outset gray;
  z-index: 5;
  /* To be sure they appear in front of all other elements. */
  -moz-border-radius: 5px;
  border-radius: 5px;
  /* To round the corner. */

It's supposed to give little rectangles like this: My tooltip test

When they are as we want, we can mask them by adding display: none;


Now the objective is to make the tooltips readable only under the mouse cursor. This is the goal of the pseudo-class :hover wich is used to indicate the style when the mouse is over an element. It's often used to personalise the links colors or underlines under the mouse pointer, but is can be used on any other element. Except of course in IE <7, :-) in this case, it's forced to use Javascript like in the 2d part of this article.

ul.links a:hover span
  display: block;

Now the tooltips will only appear when the mouse is over the links containing them. See an tooltip example in CSS.

Let's see now a very close example, using Javascript and useful to make an element appear after a click:

<a href="..." onclick="javascript:show('info')>test<span id="info">Description will be visible on a click. :-)</a>

It's necessary to put in a Javascript file the show function, which displays element if hidden, and hide if shown:

function show (id)
  var e = document.getElementById (id);
  if ( == "none") = "block";
  else = "none";

Starting from this Javascript example, we can create all sorts of menus or tooltips. But we can also do the trick only with CSS.

-> For more menu examples, see the menu tutorial on AlsaCréations (in french).

cafĂ© Did this article help you? 
Buy me a coffee!

Leave a comment (all comments are moderated, don't waste time with spam)

Azure Dev