Shape brain Slice 1Created with Sketch. Slice 1Created with Sketch. Slice 1Created with Sketch. menu 1433522600_bubble + 1433522600_bubble copy Thumbs up icon 15

How to Build CSS-only Tooltips

Written on: Oct. 6, 2016

Tooltips can be a great enhancement to an application's user interface, perhaps providing more context to a link or additional help text to a form label, all without adding visual clutter.

We have had them in our digital asset management system Asset Bank for a while now, and have traditionally implemented them using the Javascript-powered tooltips from Bootstrap. It always seemed a little overkill to rely on JavaScript for something as simple as showing some content on hover, so during some recent work we had a look around and discovered a number of great examples of CSS-only tooltips out there like Hint.css and Balloon.css. I felt like a challenge though, so opted to try rolling my own. Here's how I went about it.

The first step was to define the HTML, and I kept this nice and simple by putting the tooltip message in an 'aria-label' attribute, I also gave it a ‘tip’ class to identify it as having a tooltip:

<a href="#" class="tip" aria-label=“Some text for my tooltip">My link</a>

We knew we were going to want to absolutely position our tooltip relative to our parent ‘tip’ element, so we gave it relative positioning:

.tip {
    position: relative;

Next, we needed some kind of child element to form our actual tooltip, and to keep the markup simple I opted to use the ::before psuedo element of the parent ’.tip’ element, and populate that with the content from our aria-label attribute using the CSS ‘attr()' function - browser support for attr() is surprisingly good when used with the content property, going right back to IE8:

Now we obviously don’t want our tooltip to be permanently visible, it should only show up when you hover over the element or if the element receives focus (for the benefit of keyboard users), and only then after a small delay (to prevent it being accidentally triggered if you mouse past the element). We can achieve this by using css transitions to animate the visibility of the tooltip on hover:

For a finishing touch I added a small arrow to point from the tooltip to the element that triggered it. We’ve already used the ::before pseudo element, but we still have the ::after psuedo element, so we’ll use that to create a triangle with CSS:

That’s left us with some duplication in our CSS, so let’s do some refactoring to trim things down a little, giving us our final version:

There you have it, a simple CSS-only tooltip - one less thing to rely on JavaScript for. 

Written by