1

I understand that display: inline-block will cause a parent element to "shrink" to the width of the largest child element. This is exactly what I want if the largest element is an element like <img />.

However, if a line of text happens to be really long, it expands the width of the parent.

<div class="hi">
    <img src="http://placehold.it/350x150" />
    <div class="longtext">
        Eu duis eram anim senserit. Quae deserunt voluptatibus ex noster nam eu sunt laboris ea consequat ut amet litteris, ingeniis hic sint, et elit voluptatibus te legam do possumus, fugiat sempiternum tempor irure laboris, possumus tamen sunt expetendis quid.
    </div>
    <div class="short">wow</div>
</div>

Fiddle so you can see the problem.

How can I force a really long line of text to take the width of the parent, which is in turn taking the width from a child element?

The closest I can get to what I want is position: absolute but it takes the text out of the block-level (pushing everything up).

Fiddle.

  • Check out [this answer](http://stackoverflow.com/questions/12747045/css-shrink-a-parent-div-to-fit-one-childs-width-and-constrain-the-width-of-th), if I understand your question correctly, the first answer should solve your problem. – MTCoster Jan 31 '15 at 18:18
  • This is exactly what I want. I was hoping I wouldn't have to resort to using CSS tables, however. I guess that's the only solution out there except for, I guess, `max-content`. – Haven Lovell Jan 31 '15 at 18:21
  • Technically it's not a table, just a set of rules that's commonly used in tables (by default actually) which happen to do the trick in this situation. – MTCoster Jan 31 '15 at 18:22

2 Answers2

0

@MTCoster, your link gave me an idea.

If you fiddle with the width, you can set its width to the same as the parent dynamically.

Just like in the link, width: 1px compresses the table to the size of the smallest single word. Then min-width: 100% expands it to the width of the parent. And only 2 lines!

.longtext {
    width: 1px;
    min-width: 100%;
}

Adding word-wrap: break-word; is even better, because this will prevent a really long word from expanding the div beyond its parent.

Updated Fiddle.

Thanks a lot!

0

If you wrap div around the longtext and short div's you may get what you want?

HTML:

<div class="hi">
    <img src="http://placehold.it/350x150" />
    <div class="longtext">
        <div>
            Eu duis eram anim senserit. Quae deserunt voluptatibus ex noster nam eu sunt laboris ea consequat ut amet litteris, ingeniis hic sint, et elit voluptatibus te legam do possumus, fugiat sempiternum tempor irure laboris, possumus tamen sunt expetendis quid.
        </div>
        <div class="short">wow</div>
    </div>
</div>

http://jsfiddle.net/5mof1pku/

chris
  • 216
  • 1
  • 2
  • 7