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

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.

Put another way, the browser renders the container on the initial cascade. It doesn’t reflow the document when a child wraps.

That’s why the container doesn’t shrink-wrap the narrower layout. It just continues on as if nothing wrapped, as evidenced by the reserved space on the right.

The maximum length of the horizontal white space is the length of the element(s) that the container was expecting to be there.

In the following demo, whitespace can be seen coming and going as the window is re-sized horizontally: DEMO

You’ll need a JavaScript solution (see here and here)… or CSS media queries (see here).

When dealing with wrapping text, text-align: right on the container may be helpful in some cases.

Leave a Comment