Search code examples
csshtmltooltip

Trouble Getting Tooltip Width Correct Using CSS


I've looked at various solutions to this and can't seem to get anything to work. I hope I'm missing something simple. What I want is for a tooltip width to use only what is needed, then wrap when a max-width is reached.

Here's my CSS:

<style>
    .tooltip {
        position: relative;
        display: inline-block;
        width: 20px;
        height: 20px;
        background-color: steelblue;
        color: yellow;
        border: solid;
        border-width: 1px;
        border-radius: 50%;
        text-align: center;
        cursor: help;
    }
        .tooltip:before {
            content: '?';
        }

        .tooltip .tooltiptext {
            visibility: hidden;
            position: absolute;
            display: inline-block;
            max-width: 300px;
            background-color: black;
            color: #fff;
            text-align: left;
            border-radius: 6px;
            z-index: 10;
        }

        .tooltip:hover .tooltiptext {
            visibility: visible;
        }
</style>

And here's my HTML:

<div class="tooltip">
    <div class="tooltiptext">
        I want this to wrap only after 300 pixels.
    </div>
</div>
Blacklist

What happens is it always wraps to fit only the widest word, making the max-width setting meaningless. Any assistance would be appreciated.


Solution

  • The problem is that you're trying to cram the tooltip inside a container with 20px width. It simply doesn't have any wiggle room!

    For a solution, move the .tooltiptext out of the .tooltip. The CSS can mostly stay the same.

       .tooltip {
            position: relative;
            display: inline-block;
            width: 20px;
            height: 20px;
            background-color: steelblue;
            color: yellow;
            border: solid;
            border-width: 1px;
            border-radius: 50%;
            text-align: center;
            cursor: help;
            overflow:visible;
        }
            .tooltip:before {
                content: '?';
            }
    
            .tooltip + .tooltiptext {
                visibility: hidden;
                position: absolute;
                display: inline-block;
                max-width: 300px;
                background-color: black;
                color: #fff;
                text-align: left;
                border-radius: 6px;
                z-index: 10;
            }
    
            .tooltip:hover + .tooltiptext {
                visibility: visible;
            }
    <div class="tooltip">
    </div>
    <div class="tooltiptext">
      I want this to wrap only after 300 pixels.
    </div>
    Blacklist