timo
timo

Reputation: 2169

How do I prevent multiline text from filling the entire width of the parent element

Suppose I have a container element that has a set width. I have a content element with a display inline-block that can contain some text. This text could be so big that it has to be filled over several lines. The problem with this is that default behaviour for multiline text is that it grows the element to the complete width of the parent element.

Imagine the following example:

HTML:

<div class="container">
  <div class="content">
    Firstreallongword11 Secondalsolongword22 Thirdwordthatisconsiderablylonger
  </div>
</div>

CSS:

.container {
  width: 260px;
  border: solid blue 1px;
}
.content {
  display: inline-block;
  background: red;
}

Because these are long words, they will be positioned over multiple lines. What I would expect for the .content element, is that it would grow to the maximum width of the largest word on one single row. But as you can see, because it consists of multiple lines, the element grows to the max width of .container .

FIDDLE

What I want to achieve is, .content gaining the width of the largest item on a single row, as it would with one single lin:

FIDDLE

Is there any way to achieve this with pure css/html?

Upvotes: 6

Views: 2924

Answers (1)

Johannes
Johannes

Reputation: 67748

The simple answer is: No, you can't do that with pure CSS.

But here is a solution anyway, which is a bit of a hack: It uses display: table-cell; for the .content element, and a rather small width value (which will adjust to the actual value of the longest word and acts like a min-width setting in this case):

.container {
  width: 260px;
  border: solid blue 1px;
}
.content {
  display: table-cell;
  width: 100px;
  background: red;
}
<div class="container">
  <div class="content">
    Firstreallongword11 Secondalsolongword22 Thirdwordthatisconsiderablylonger
  </div>
</div>

Upvotes: 4

Related Questions