0

Imagine an element containing only text:

<p>
  Foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar foobar
</p>

I want the node to take up no more than, say, 100px in width. This is trivial to achieve with max-width: 100px:

p {
  display: inline-block;
  max-width: 100px;
}

However, I also want the container to hug the text closely - to take up the minimum amount of horizontal space required. With only max-width specified, if the line breaks fall in a specific position, the container will still take up max-width amount of space, even though it could be even narrower to fit the text:

A text container with max-width taking up more than strictly required to fit the text

I tried using a combination of fit-content, max-content, min-content with min-width, max-width and width, but none of them really achieve what I want.

When adding min-content, the container will hug the text closely, but that would also require me to add a min-width to make sure the there aren't line breaks on every single line.

The problem with adding a min-width is I can't know upfront what the smallest content in the container could be – if it's just a single word OK, I only want it to take up as much space as needed to hug that word. So a min-width of, say, 50ch would break this behavior.

CodePen

Elise
  • 5,086
  • 4
  • 36
  • 51
  • I think the reason is that the div can't hold three 'Foobarbaz', you can add `font-size: 15px;` and see the result. Or I misunderstand something :) – codewithhong Jun 15 '22 at 07:33
  • So essentially, you want to base the computed width on the number and length of the words in the content. I believe this isn't possible with just CSS. – Noam Jun 15 '22 at 07:41

0 Answers0