I am trying to figure out if there is a way to force an inline-block element to fit the true size of the text inside of it, but I can't find any way to do this. Once text reaches the end of line and wraps to a new one, the inline-block width appears to automatically stay at the maximum allowed width of the container. If you insert a < br > or otherwise manually line break, the size of the inline-block is what I expect it to be.
Unfortunately, my use case does not allow me to manually update the content and also must be responsive, so line breaks may occur between different words at different viewport widths or devices--so I'm hopeful that I can accomplish this with CSS or reliably with JS.
The snippet below illustrates this. The grey text does not line wrap, and therefore is exactly the width of the contained text. The red text does line wrap, and maintains the maximum width of the container even though there is white space to the right of both the first and second lines. The green text acts like I want it to, but I have used a < br > just for demonstration.
Is there any way to make an element actually match the size of the text inside it? Any help would be appreciated, or a definitive no would also be great so I can stop searching haha.
.container {
width: 200px;
background-color: #000;
}
.ib {
display: inline-block;
}
.grey {
background-color: #ccc;
}
.red {
background-color: #e00;
}
.green {
background-color: #0e0;
}
<div class="container">
<span class="ib grey">
Short text.
</span>
<span class="ib red">
Longer text with alongwordforanewline.
</span>
<span class="ib green">
Longer text with<br />alongwordforanewline.
</span>
</div>