Explain Codes LogoExplain Codes Logo

Add line break within tooltips

html
responsive-design
css
accessibility
Alex KataevbyAlex Kataev·Sep 19, 2024
TLDR

To create line breaks in tooltips, use 
 or 
 within the title attribute.

<a title="First line&#013;Second line">Hover over me!</a>

Place these HTML entities anywhere you want a new line, and the tooltip will display the text on separate lines when you hover over the link.

Alternative methods and other tools

Beyond just placing HTML entities, there's a world of options for managing tooltips and creating line breaks. Let's get into the weeds.

CSS for fancy text formatting

Utilize CSS to gain granular control over the formatting inside custom tooltip implementations:

/* CSS that wiretaps into the Matrix */ .tooltip-inner { white-space: pre-wrap; /* Allows for spaces and line breaks of course */ }

Attach this to your tooltip content, and then press Enter to break lines in your text editor. Voilà! Tooltip text with natural line breaks.

Tooltip plugins: Hover on steroids

In case you're using tooltip plugins like Bootstrap, data-html="true" will let you get fancy:

<a href="#" data-toggle="tooltip" data-html="true" title="Line1<br>Line2">Hover Over Me!</a>

Here, the title attribute speaks HTML fluently, making complex formatting possible. The <br> tag obliges to become your line break!

Formatting: Not just for black tie events

If your tooltips require formatting – say, blocks of code – then the pre tag and white-space: pre-line; CSS property will dance to your tunes:

/* CSS conducting formatting à la Beethoven */ .tooltip-inner { white-space: pre-line; /* Ready to swing with both breaks and spaces */ }

And your HTML:

<a href="#" title="<pre>Line1\nLine2</pre>" data-html="true">Hover Over Me!</a>

Making tooltips more human-friendly

Accessibility is important, just like the first coffee in the morning. Use the aria-describedby attribute and follow WAI ARIA Practices. Let's help our assistive technologies buddies out!