In my previous post I blogged about truncating content in a DIV only using CSS. I wanted to revisit that and show you how to add a tooltip to that same truncated div using CSS. The theory is that if you truncate the text, you'll want the user to be able to see the full text. One way to do that is by adding a tooltip.

I was surprised that divs don't intuitively support tooltips, but I did some searching and . found a cool way to do it..

I'm going to build off the example from my previous post, so we can assume we already have a div with content that is truncated.

Now let's add two new CSS elements. One for tooltiptrigger, and one for tooltiptext.

First, add this:

view plain print about
1.tooltiptrigger .tooltiptext {
2 visibility: hidden;
3 background-color: grey;
4 color: white;
5 position: absolute;
6 z-index: 1;
7}

Here, we're creating a CSS hierarchy where the tooltiptext must be inside the tooltiptrigger. The tooltiptext is hidden by default, has some background color in grey, and some foreground color in white. The z-index is set to 1 so that it shows up on top of other elements of the page . And finally, the position is absolute.

Let's add another set of CSS:

view plain print about
1.tooltiptrigger:hover .tooltiptext {
2 visibility: visible;
3}

This means that whenever we hover over the tooltip trigger, the tooltiptext will become visible.

Let's go back to the HTML

view plain print about
1<div class="truncatedDiv tooltiptrigger">
2 This is something with a lot of text. The Quick Brown Fox Jumped over the Lazy Dogs. The whole purpose here is to extend the text beyond multiple lines with a lot of space so that we can demonstrate truncating it inside a div that has multiple lines and extra dots.
3 <div class="tooltiptext">
4 This is something with a lot of text. The Quick Brown Fox Jumped over the Lazy Dogs. The whole purpose here is to extend the text beyond multiple lines with a lot of space so that we can demonstrate truncating it inside a div that has multiple lines and extra dots.
5 </div>
6</div>

The hierarchy of the HTML is that the tooltiptext is nested inside the tooltiptrigger div. The truncated text will show the tooltip when we roll over it.

I do not like that we are replicating the full text in two sections here, but if we were building something in a single page framework, or generating the HTML from a service we could easily solve that.

Run this code:

And now rollover the text:

Walah! It works. What I did not devote time to placement of the tooltip, but we could easily do so using CSS positioning elements.

Play with it over on Plunker.