By default, when text wraps, the width of the container becomes the max width. Instead, I want the width to fit the wrapped text.
div {
border: 1px solid red;
max-width: 100px;
display: inline-block;
}
<div>
qwertyuiop
</div>
<div>
qwertyuiop qwertyuiop
</div>
In the example above, I want the 2 boxes to have the same width. Is this possible without JS?
2
Answers
Yes, it is possible to achieve the desired behavior where the width of the container fits the wrapped text using CSS only. You can use
min-content
for thewidth
property to achieve this. Here’s how you can do it:Make the container fit the text with lineWrapping and ensure both boxes have the same width, you can use a combination of inline-block and some adjustments to the display propertie.
https://developer.mozilla.org/en-US/docs/Web/CSS/white-space
https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_text/Wrapping_breaking_text
https://developer.mozilla.org/en-US/docs/Web/CSS/word-break