Mikhail Kornienko Mikhail Kornienko - 6 months ago 29
CSS Question

Make container shrink-to-fit child elements as they wrap

I'm trying to figure out how flexbox works (supposed to work?…) for cases like below:

<div class="holder">
<div class="child">At a glance</div>
<div class="child">After coverage ends</div>
<div class="child">Forms & documents</div>
</div>

<br><br>

<div class="holder v2">
<div class="child">At a glance</div>
<div class="child">After coverage ends</div>
<div class="child">Forms & documents</div>
</div>

<br><br>

<div class="holder v2">
<div class="child">At a<br>glance</div>
<div class="child">After coverage<br>ends</div>
<div class="child">Forms &<br>documents</div>
</div>


And accompanying CSS:

.holder {
width: 500px;
background: lightgray;
display: flex;
flex-direction: row;
justify-content: space-between;
flex-wrap: nowrap;
}

.v2 {
width: 320px;
}

.child {
display: inline-block;
border: 1px solid black;
padding: 30px 0px;
text-align:center;
}


JSFiddle here

The problem is that when there's enough space to fit elements, I'm getting a nice tight-fitted children, with even spacing between. (first, top div block)

However, when there's not enough space and text inside children starts wrapping, it all kinda goes in a weird direction - children are not tightly fit anymore, and even though after wrapping, there's enough space around flex children, because there are not properly fit anymore, space-around doesn't really have a chance to work as well (second div block)

However still, IF I add manual line breaks at places where the automatic line breaks occur, everything gets laid out as it "should"… (bottom, third block)

What I'd like is to always have children tightly fitted within their boxes (black borders), and whatever space is left, would be distributed evenly between them, without me having to add manual line breaks (which is not an option in my case)

Is it possible at all?…

Answer

In CSS, the parent container doesn't know when its children wrap. Hence, it continues scaling its size oblivious to what's going on inside, and doesn't re-calculate its width to shrink-wrap its content.

You'll need a JavaScript solution, or possibly CSS media queries, to achieve the fit you want.

When dealing with wrapping text, a possible solution is text-align: right on the container.

Here are some more details: http://stackoverflow.com/a/32811002/3597276

Comments