I created SCSS Tooltips, a simple Sass mixin, to make this task even easier. You can download a zip file or check out the code on github.
- Configurable position
- Smooth fading
- No extra HTML elements
- Overridable by including the mixin on another selector
See the Pen SCSS Tooltips by David Tintner (@dmtintner) on CodePen.
How does it work?
There are a few interesting things going on inside of the mixin that I’ll dive into a little deeper.
Automatically setting the text color
The text color for the tooltips is automatically configured to be light or dark based on the background color parameter that we pass into the mixin. Using a Sass color function, I check for the the lightness of the color, and if it is more than 50% we want to contrast the dark background with light text and vice versa. You can configure what color you want for the light and dark text in the settings variables.
Handling variable size of the content
If the tooltips were limited to be a single line of text, I could have just used a fixed amount to position them relative to the parent element. However, I wanted to make sure that the content could be any size and any number of lines.
So to position them dynamically, I used
transform: translateY(100%) to move the tooltip body up or down equal to its entire height.
Making them overridable
If you look into the code, you’ll notice a couple of extra, seemingly unnecessary CSS properties. On each direction variation, all 4 positions, top, bottom, left, and right are declared, however 2 of them are set to auto. This is to ensure that if a tooltip was created, but then overridden in a later selector (as I often find myself doing to prevent it from going off the screen) it will still work fluidly.
What else is out there
There are some other nice Sass tooltip projects already out there: