I came across this cool, easy to write CSS-only tooltip while agonizing over some jQuery animated tooltip I was writing for a project. I liked it because it was easy to make, with absolutely no event-driven JavaScript. This keeps the animation & style where it should be, in the DOM. So this could easily be used in any client app framework, like Angular.

The other great aspect is that you can put the tooltip text into a data attribute, which will be loaded into the DOM.

So let’s jump right on in to the code. However, if you are in a hurry, go take a look at the code in Plnkr, CSS only ToolTip

Let’s take a look at this simple markup. This is a simple little HTML5 SMALL Element with a SPAN inside it. Notice how it uses the ‘data-‘ attribute, ‘data-tooltip=”The tooltip text, wow this is amazing.” to contain the actual tooltip text.


<small data-tooltip="The tooltip text, wow this is amazing.">
<span>Some FOO text</span>
</small>

That’s it for your markup.

Now for the CSS. You’ll add a style for the data-tooltip attribute selector. Assign it a relative position and z-index to make sure it’s above the element. Then add a CSS selector for the same element, with hover:after. Here is the cool trick, add this to the CSS a content attribute containing the attr(data-tooltip).


[data-tooltip] {
     position: relative;
     z-index: 10;
} 
[data-tooltip]:hover:after {
     content: attr(data-tooltip);
}

 

That was super easy! Now you can style it up yourself with come some transitions and whatever.