7

HTML code:

<div id="container">
    <div id="first">
        foo bar baz foo bar baz
        foo bar baz foo bar baz
    </div>
    <div id="second">
        Foo
    </div>
    <div id="third">
        foo bar baz foo bar baz
        foo bar baz foo bar baz
    </div>
</div>

CSS code:

body {
    text-align: center;
}
#container {
    display: inline-block;
    background: lightcyan;
}
#first {
    display: inline-block;
    background: lightgreen;
}
#second {
    background: orange;
}
#third {
    width: 30%;
    display: inline-block;
    background: lightblue;
}

I am trying to ensure that the entire div#container shrink-wraps around div#first. The above code works as expected. See this demo: http://jsfiddle.net/HhrE6/

However, as I add more text into div#third, the shrink-wrap breaks. See the broken demo: http://jsfiddle.net/n4Kn2/

  1. Why does this happen?
  2. How can I prevent this from happening?
Lone Learner
  • 18,088
  • 20
  • 102
  • 200
  • Is there a reason you use `inline-block`? Since you have all the divs under each other, why not use `block`? – GreyRoofPigeon Jul 07 '13 at 11:18
  • @LinkinTED I am using `inline-block` for div#container to shrink-wrap around div#first. If I use `block` for all divs, they will expand to cover the entire width of the browser. – Lone Learner Jul 07 '13 at 11:21

1 Answers1

2

In this example you have the width of the container that depends on the width of the content, which, in turn, depends on the width of the container. That's why the renderer can't take into account the actual width of the #third block in the time it calculates the width of the #container.

According to the CSS spec, the width of an inline block is calculated as

min(max(preferred minimum width, available width), preferred width).

where the preferred width is calculated

by formatting the content without breaking lines other than where explicit line breaks occur

So the width of the container becomes the width of the #third block (as the widest one) if its content is laid out without any line breaks, and then the actual width of the #third block is set to 30% of this width.

Ilya Streltsyn
  • 13,076
  • 2
  • 37
  • 57