CSS only tooltip using attr()
Usually we'd choose to use JavaScript or some little weight plugin to show tooltips. But it's possible to create toolips like these on hover, using CSS only :)
Note: Before we proceed, please be aware that tooltips aren't that great for accessibility. Use them only if the tooltip information is not very important.
Of course we can do this by adding the tooltip content within a span
element, position is using absolute
position, set visibility
to hidden
and then show on hover
.
But it's not good practice to add that invisible text within the paragraph. Using JavaScript, we could add the tooltip content using a "title" attribute to show it.
Can we do this in CSS though? Yes! Using the attr()
CSS function. We can access the content in title attribute using content: attr(title)
Now you can reuse this tooltip class by adding it to any element with a title attribute.
Note that the attr()
function can be used with any CSS property, but support for properties other than content
is experimental.
Here's the demo on Codepen.
📘 Complete Guide to CSS Flex and Grid
If you loved this write-up and how it was explained, you’ll absolutely love my eBook CSS Flex and Grid. Check it out!
📨 Newsletter suggestion
I love Tailwind CSS. If you love it too, I highly recommend subscribing to this one 👇
Tailwind Weekly: Weekly newsletter about all things Tailwind CSS. New issue every Saturday.