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.

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

.tooltip{

cursor:pointer;

display:inline-block;

position:relative;

border-bottom:1pxdotted#000;

text-decoration:none;

}

.tooltip .message{

display:none;

position:absolute;

background:white;

left:0;

border:1pxsolidblack;

padding:3px;

}

.tooltip:hover .message{

display:inline-block;

}

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.

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.