ThomasAJ
ThomasAJ

Reputation: 721

How to make an inline-block parent's width be wrapped around it's children?

I have a parent div with display: inline-block and two floated child divs. When there is enough space for them to be placed next to each other the parent div's height and width are totally determined by the children.

But when the space is insufficient - making the child wrap to the next line and the elements be stacked vertically, the parent div's width remains as it was just before the children stacked instead of adapting to the size of the largest child.

How can I solve this so the parent still wraps instead of having a width that is too large?

See JSFiddle

<div id="parent">
 <div></div>
 <div></div>
</div>

#parent {
    display: inline-block;
    border: solid 2px;
    padding: 10px;
    background-color: #aaaaaa;
}

div > div {
    float: left;
}

div > div:first-child {
    width: 200px;
    height: 200px;
    background-color: yellow
}

div > div:last-child {
    width: 300px;
    height: 300px;
    background-color: blue;
}

Upvotes: 2

Views: 2378

Answers (2)

Shikkediel
Shikkediel

Reputation: 5205

This is caused by not clearing the floats and as far as I've been able to read, there's no direct solution to do this in a fully responsive way without using JavaScript.

But with fixed dimensions, there is an approach that will clear the floats and wrap the parent :

http://jsfiddle.net/cfL491Lc/

@media screen and (max-width: 555px) {
    div > div:last-child {
        clear: left;
    }
}

With the following logic : breakpoint = width of divs + padding + margin on body + 19px scrollbar.

If there's no scrollbar present, it will wrap a bit too early but that's the limitation of media queries. Depending on the surrounding content (especially the total height) another query might be necessary.

Upvotes: 1

Lakshminathan
Lakshminathan

Reputation: 23

I'm not getting your question. In the code which you gave the outer div's height and width are determined by the inner divs

when stacked horizontally :

outer width = sum of inner widths outer height = greatest of inner heights

<div style="width:auto;height:auto;display: inline-block; border: solid 2px; padding: 10px; background-color: #aaaaaa;">

    <div style="float: left; width: 200px; height: 200px; background-color: yellow;">
    </div>

    <div style="float: left; width: 80px; height: 30px; background-color: blue;">
    </div>


</div>

When stacked vertically

outer height= sum of inner heights outer width= greatest of inner widths

<div style="width:auto;height:auto;display: inline-block; border: solid 2px; padding: 10px; background-color: #aaaaaa;">

    <div style="float: left; width: 200px; height: 200px; background-color: yellow;">
    </div>
<br>
    <div style="float: left; width: 80px; height: 30px; background-color: blue;">
    </div>


</div>
What do you want to change in this?

Upvotes: 0

Related Questions