CSS Width / Max-Width on Line Wrap?

#tooltip
{ 
    position: absolute;
    width:auto;
    min-width:50px;
    max-width:250px;
    padding:10px;
    background-color:#eee;
    border:1px solid #aaa;
}

Based on this style I would expect my tooltip to shrink or grow to fit the content, down to 50px or up to 250px. However, the max-width property seems to be over-riding my width property when a content wraps to the next line. It is an aesthetics thing when the word at the end of a sentence is long, it looks like it leaves a bunch of padding (see screenshot). Is that the normal behavior?

enter image description here


Yes, that's the normal behavior.

A browser will try to flow your text inline within the box until it reaches its maximum allowed width of 250px, then wrap to the next and subsequent lines any text that cannot fit on the first line. (If there is not enough text to reach the maximum width, then width: auto causes the box to shrink to fit just that amount of text.)

However, the box will not shrink again to fit the text after wrapping it, because text wrapping just doesn't work that way. This means the box's width is computed as 250px, and only because your CSS states that it can only be 250px at most. It's not computed to some smaller value equal to the width of the text after wrapping then overridden by max-width.

I don't think there is anything you can do to change this behavior.


Try using one of this:

width: max-content;
width: min-content;
width: available;
width: fit-content;

They are not 100% compatible, but prefixes fix that problem more or less.

Source: https://developer.mozilla.org/docs/Web/CSS/width