Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shrink wrap breaks as I add more text into a child DIV element

Tags:

html

css

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?
like image 703
Lone Learner Avatar asked Jul 07 '13 11:07

Lone Learner


1 Answers

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.

like image 119
Ilya Streltsyn Avatar answered Sep 22 '22 14:09

Ilya Streltsyn