Friday 29 July 2011

Basic CSS Tool Tip

There are a lot of tool tips out there but I've grown to like this implementation as it's so simple and extensible.

CSS code:

span.tool {
  position:relative;
  cursor:help;
}
span.tool span.tip {
  display: none;
}
span.tool:hover span.tip {
  display: block; 
  z-index: 100; 
  position: absolute;
}

HTML code:

<span class="tool"> 
 <label for="txtExample">Example</label> 
 <span class="tip">The tip text goes here.</span> 
</span> 
<input type="text" name="txtExample" id="txtExample"/>

How it works

There are 2 span elements at work here; tool & tip. Tool is positioned relative to the page. Tip is not displayed (display: none) on the page. On the tool hover event, the tip's attributes are changed; 
  • The tip is now displayed (display: block) i.e. visible on the page 
  • z-index is set - this ensures that the element shows in front of anything else on the page 
  • Position is set to absolute and top and left attributes are set. This allows us to put the tip wherever we like. This is relative to the containing span (tool). 
There is no styling in the code above so it's recommended to add some styles of your choosing to the span tip (at least a background-color so that the tip text does not go over other text on the page!). I'd add all styles to the span.tool:hover