How To Make Custom Tooltips With CSS
title attribute allows you to add tooltips to your elements, these are great for accessibility, or just making your webpage more self explanatory.
But they look kind of boring, enter this tutorial!
First let's add a custom attribute to the element we want to give the tooltip. For example's sake I'm going to be using an anchor tag, but this should work on any element.
data-title tag contains the text we want to display on the tooltip. Custom HTML attributes must be prefixed with
data- otherwise they won't register.
Now let's beak out the CSS!
*[data-title] selector selects any element with the attribute
data-title defined, it doesn't matter what the value of
data-title is, just as long as it's defined.
position: relative property has to do with how we're positioning the tooltip, I'll talk about that later.
Next the styles for the actual tooltip:
*[data-title]:hover selects any element with the attribute
data-title defined, that's being hovered over.
If you don't know what
::after means, it inserts something after the content of the selected element, you also might want to check some documentation I found about it.
When combined with the
position: relative of the element, and the
position: absolute of the tooltip it allows you to position the tooltip relative to the element its applied to, using the
So let's do just that:
top: 20px positions the the top of the tooltip 20 pixels bellow the element its applied to.
Now let's add the actual text of the tooltip:
The CSS attr() function retrieves the the value of an attribute of an element, the
content property sets the text content of the tooltip. So
content: attr(data-title) sets the text of the tooltip to its
Congratulations! You now have a functioning custom tooltip, but right now it isn't much better than the vanilla HTML tooltips, so let's spice it up with some style!
From here on out all of the styling is optional, feel free to decorate the tooltip however you want!
First let's add a background:
I'm going to be using a nice blue color for my background.
Right now the text looks a bit mushed, so let's add some padding:
Now currently the tooltip inherits its foreground color from the element its applied to, so let's fix that:
Alright, now finally let's add a border:
Now your custom CSS tooltip is finished! Hope you found this helpful, enjoy!