Explain Codes LogoExplain Codes Logo

How can I use a carriage return in a HTML tooltip?

html
responsive-design
best-practices
accessibility
Nikita BarsukovbyNikita Barsukov·Jan 17, 2025
TLDR

To add a line break in a tooltip, use 
 or 
 each representing a carriage return and line feed:

<a title="Line 1&#013;&#010;Line 2">Hover for tooltip</a>

Now, your tooltip will display "Line 1" above "Line 2".

Understanding HTML tooltip plays with carriage returns

What on Earth is a tooltip?

An HTML tooltip is simply text displayed when a mouse hovers over an element — usually created using the title attribute.

How to make text play Hide-and-Seek?

To split text onto different lines, we can use HTML entity codes like &#10;, &#13; directly in the title attribute or merely press the Enter key where we desire the line break.

Cross-browser compatibility? Yes, we thought of that!

However, different browsers interpret entity codes differently; Firefox prefers &#13;. To keep things consistent, opt for &#13; and &#10; which provide browser-wide consistency.

Hold on! What about JavaScript?

Not to worry, in JavaScript, rather than using \n, try \x0A, which represents a line feed. You may need hexadecimal escape sequences.

What not to use?

Stay away from <br />, &013;, \r\n, or Environment.NewLine: They're not recognized in the title attribute.

Official Guidelines and Accessibility Concerns

Always follow HTML specifications and standards. Plus, a simple tooltip with line breaks enhances accessibility and user experience.

Additional techniques and edge cases in the wild

Dynamic content and JavaScript

When dealing with dynamic web content, JavaScript becomes handy, but it's not quite the same. Here's how:

var myElement = document.getElementById('myElement'); // Tooltip that's learning Yoga ;) myElement.setAttribute('title', 'First line\nSecond line');

Crafty CSS

Why not go beyond the title attribute and hop into the world of CSS? With CSS, you can style tooltips and even use HTML inside them. But remember, with great power comes great responsibility.

.tooltip { position: relative; display: inline-block; } .tooltip .tooltiptext { visibility: hidden; width: 120px; background-color: black; color: #fff; text-align: center; padding: 5px 0; border-radius: 6px; /* Positioning */ position: absolute; z-index: 1; } .tooltip:hover .tooltiptext { visibility: visible; }

The Good, the Bad, and the Tooltip

  • Do keep it simple and sweet for basic tooltips.
  • Don't use tags other than recognized entities within title.
  • Do consider accessibility: the end goal of tooltips.
  • Don't overcomplicate things with JavaScript when simple entities will suffice.