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
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:
More UX & Frontend goodness
- Introducing: The Hacking UI Master Class Series - January 17, 2017
- Influencing an industry and building a personal brand with Khoi Vinh (Principal Designer, Adobe) - December 22, 2016
- How to grow a blog and remain true to your audience – Chris Coyier (CSS-Tricks & CodePen) - November 24, 2016
- The ups and downs of dominating a niche – Harry Roberts (CSS Wizardry) - November 10, 2016
- The best decision we ever made - October 31, 2016
- The teacher who never stopped learning – Kelsey Ruger (SPA alum) - October 25, 2016
- The musician who turned a side project into a multi-million dollar company – David Okuniev (Typeform) - October 20, 2016
- The freelance designer that stopped selling his time – Peter Nowell (Sketch Master) - October 11, 2016
- A complete step-by-step guide to set up HTTPS on your website - October 10, 2016
- The mission to give everyone their own home on the Internet – with Matt Mullenweg (Automattic, WordPress) - October 6, 2016