2

Let's assume we have a <span> element with the following css:

span {
  display: inline-block;
  max-width: 250px;
}

In case our text is short and it fits in only one row, the width of the span will have exactly the width of the content. Otherwise, if the text is larger and it needs to break on multiple lines, the width of the span will be exactly the max-width (250px) and not the width of the content.

I would like my span to always have the width of the content itself. Is this possible somehow?

span {
  display: inline-block;
  max-width: 250px;
}
<span style="background-color: green">Lorem ipsum</span>
<br>
<br>
<span  style="background-color: red">Lorem ipsum dolor sit amet, consectetur adipiscing elit</span>
Andrei Rosu
  • 1,169
  • 2
  • 10
  • 26
  • 2
    This happens because on the first line, the text `consectetur` tries to fill up the whole first line. When it's not able to, it goes to the line below leaving the whole width used on the first line. There's no going around this. If you tell us *why* you need to do this we might give you alternatives. – Alexandre Elshobokshy Oct 02 '20 at 08:31
  • Oh, and your question was asked before here : https://stackoverflow.com/questions/41389292/display-inline-block-does-not-make-width-as-small-as-possible-with-wrapped-cont – Alexandre Elshobokshy Oct 02 '20 at 08:33

1 Answers1

-1

span {
  display: inline-block;
  max-width: 250px;
  word-break: break-all;
}
<span style="background-color: green">Lorem ipsum</span>
<br>
<br>
<span  style="background-color: red">Lorem ipsum dolor sit amet, consectetur adipiscing elit</span>
Yalcin Kilic
  • 778
  • 3
  • 14
  • This is still not the result the OP asked for.... And if it is, then it's a duplicate i.e the question I linked in the comments. – Alexandre Elshobokshy Oct 02 '20 at 08:35
  • There would be a problem with the word-breaking (for the word "consectetur", the first part, consectet" is on the first line and the second part, "ur" is on the second line) – Andrei Rosu Oct 02 '20 at 08:40
  • @AndreiRosu yep that's what `word-break: break-all` does, take a look at the question and answer I linked under the post. – Alexandre Elshobokshy Oct 02 '20 at 08:41