The code snippet pretty much explains the issue. If I want to make a div only take as much space as its text, how can I do it if the text has wrapped into a new line???
.outer-container {
width: 600px;
height: 300px;
background: pink;
}
.text-container-bad, .text-container-good {
display: inline-block;
margin-bottom: 30px;
background: cyan;
}
<div class="outer-container">
<div class="text-container-good">
Shorter text that doesn't wrap and the container only takes as much space as the text
</div>
<div class="text-container-bad">
This is a longer text that wraps and the container takes more horizontal space thaaaaaaaaaaaan its text
</div>
</div>
2
Answers
This problem doesn’t have a straightforward CSS-only solution for all cases.
It’s a little tricky due to the way CSS works with wrapping and block dimensions. Here’s a workaround to get closer to the desired effect using CSS…
We can use
float: left
which makes the container only as wide as its content, even if the content wraps to multiple lines.There’s not an easy solution to this with CSS because of how CSS calculates the width of the divs. It doesn’t recalculate the width after rendering the line breaks.
If you you want to accomplish what the title of this post suggests, which is to make the wrapped text as wide as its container div, you can add word breaks:
This will make it so ‘tha…an’ extends all the way to the end of the first line before breaking onto the second line.