Pure CSS Tooltips

CSS Frameworks

One ironic thing about CSS frameworks is many require a JS library to work (And then sometimes they also require Jquery on top of that). One of the things they like to use JS for is tooltips. Which as I’m going to show is not always necessary.

Here is completed jsfiddle example.

Code

Tooltips are actually very easy to do with just CSS. Lets look at an example using tooltips for definitions. Lets say we have a sentence with a word we want to define.

So we have a sentence with a tooltip and a message. All we need now is three CSS rules.

The main trick of this is .tooltip:hover works even when hovering over children. So as soon as you make .message visible as long as the mouse stays on the message it will stay visible.

Improvements

This is a very simple example. Obviously adding shadow effects and possibly some animations would make it more visually appealing. Also, if you wanted to use superscripts similar to Wikipedia. You would need to remove the dotted underline and style accordingly.

A more advanced pure css example Wikipediaesque tooltip.

Caveats

There are several caveats however. First is the lack of support for touch input. This could be added by using links or giving a tabindex and the :active pseudo-class. But this means that clicking on the word will not remove the tooltip until you click somewhere else. So whether this is viable is dependent on the use case.

The second problem is positioning. JS can be used to measure whether the tooltip should be above/below or to the left/right of the target. CSS Doesn’t do a good job of handling this. This may or may not be a problem if used in a central column of text it probably won’t be much of a problem, and if you know for a fact it needs to float another direction you can add a direction class to your tooltip that handles it. The problem is there may be sometime where you don’t know exactly where the target it going to end up in relation to the rest of the page. So again it depends on your use case and on your design.