How do I add a tool tip to a span element?
Use the title
attribute to add a tooltip to a span
element:
Upon hovering, the tooltip text is showcased.
Beyond the title attribute
Whilst speedy and handy, using the title
attribute is somewhat basic. A lack of customization leaves the style and display of the tooltip up to the browser's interpretation. For a higher degree of control, we can leverage the powers of CSS and JavaScript.
Going stylish with CSS tooltips
To add style to the tooltips without involving JavaScript, CSS is your friend. With the :before
and :after
pseudo-elements, we can create visually appealing tooltips.
Accompanied by a simple span
element that houses our tooltip text:
Using this method, the tooltip gets centered dynamically based on the hovered element and displays a stylish fade-in effect.
Advanced CSS tooltip techniques
Utilizing attr() function
For dynamic tooltip text, consider embedding the text into the data attribute of your elements.
We can leverage the attr()
function to pull the tooltip text:
Smart tooltip positioning
If you want to ensure, your tooltip never goes offscreen, a little CSS technique can be helpful. With neat CSS selectors and the rule of specificity, you can have different positionings depending on where your tooltips are in the viewport.
Empowering tooltips with JavaScript and jQuery
For coders who seek special effects, event handling or additional interactions with the tooltips, JavaScript and its libraries such as jQuery UI come in handy. For instance, jQuery UI allows adjusting tooltip positioning, embedding rich content, and managing the showing/hiding delay:
This demonstrates the flexibility and control power of jQuery UI, providing wide-ranging options for your tooltip design needs.
Was this article helpful?