Search code examples
htmltooltip

How to use tab characters in html title attributes for tooltips in Chrome


I am using tab characters in a HTML title attribute for display in a tooltip, which works as I expected in Firefox (112.0.2). In Chrome (112.0.5615.138) however, this is not the case, it seems to replace tabs with spaces (or something alike), causing text to not align on different lines.

JSFiddle

<div title="X&#9;X&#10;&#9;X" style="width:50px;height:50px;background:yellow;"></div>

Chrome Firefox
Chrome Firefox

I have found this SO answer which shows use of the tab character, but this only applies when the tab characters are at the start of a line.

Is it possible, without resorting to custom tooltip elements, to display the Chrome tooltip like the Firefox one?
The title attribute specification does not say anything about tab characters (as far as I can see), so I am guessing that I am out of luck...


Solution

  • Short Answer

    In neither browser do you have the ability to modify the appearance.

    Alternative Solution (without extra DOM elements)

    However, it is possible to create an alternative without using extra DOM elements.

    /* displaying ::after element on parent element hover event */
    [data-title]:hover:after {
        opacity: 1;
        transition: all 0.1s ease 0.5s;
        visibility: visible;
    }
    /* new tooltip design */
    [data-title]:after {
        content: attr(data-title);
        position: absolute;
        bottom: -1.6em;
        left: 100%;
        z-index: infinite;
        padding: 2px;
        background-color: #f9f9fb;
        border: 1px solid #67676c;
        border-radius: 3px;
        font-size: 12px;
        font-family: sans-serif;
        color: #000;
        white-space: pre; /* you can use tab and line break this way */
        /* default hidden */
        opacity: 0;
        visibility: hidden;
    }
    /* the parent element needs to be relative so that we can position the after element absolutely relative to it */
    [data-title] {
        position: relative;
    }
    <div data-title="X&#9;X&#10;&#9;X" style="width:50px;height:50px;background:yellow;"></div>

    Note: If it's important that it doesn't have a fixed position, you can query the mouse position in JavaScript. You need to pass this to a CSS variable, for example, with names like mouse-x and mouse-y, which you can refer to in other parts of the CSS.