As seems to have become a theme in this series I'll be taking a component from jQuery UI and recreating it without using any javascript. This time we'll be looking at creating styled tooltips, you can use the title
attribute but unfortunately that cannot be styled.
Compatibility
I will be using ::after
and attr()
in order to create this element. Both of which have complete browser support.
When looking at new attributes, elements or css properties I head over to mozilla's developer site and I suggest you do the same.
::after
In CSS,
::after
creates a pseudo-element that is the last child of the selected element. It is often used to add cosmetic content to an element with the content property. It is inline by default.
attr()
The
attr()
CSS function is used to retrieve the value of an attribute of the selected element and use it in the stylesheet. It can also be used on pseudo-elements, in which case the value of the attribute on the pseudo-element's originating element is returned.
The markup
The html is quite simple we'll want to put a span
around the word we want the tooltip to be associated with. Also, we are going to add a data attribute called data-tooltip
this attribute will contain the tooltip's text.
Adding styles
When it comes to styling we only care about a couple of things, we want to make [data-tooltip]
look slightly different so the user knows it might do something and we want to style the [data-tooltip]::after
part, I've added a little animation too. We will use [data-tooltip]:hover::after
to know when to make the tooltip appear.
As always I will note, you can style this however you like. I've stuck to the jQuery UI style for this example just so it's a fair comparison but you can do whatever looks good to you.
Fin
Well there we have it. I've not posted a blog for a while, almost a year in fact, so I decided to tackle something simple this time. There are a few problems with this method such as it's possible for the tooltip to appear slightly off screen but a tiny amount of JS can fix that, we don't need an entire library.
Thank you for reading ❤️ 🧠 🧠 🦄🦄🦄 🧠 🧠 🧠 🧠 ❤️ ❤️ ❤️
Top comments (1)
This is awesome! Thanks for sharing!
I only run into trouble with
overflow:hidden
on a parent element. I've just added a rule for the parent to makeoverflow:visible
on:hover
which has possible side effects. But I assume there's no way to emulate thecontainer
property from bootstrap's tooltips without js?