Container div with float elements inside

Problem

Suppose we have a <div id=”container”> containing float:left, float:right and normal flow block and inline content. The container is given a width value.

I want the container div width to adjust to the width of the content inside.  However, the container div will only shrink to fit the non-floating elements only.  The floating elements will be either all the way out, or half out, half in, and not have any bearing on the size of the container div.

Example – Float left with fixed width container that is too small

Cause

Container divs do not resize to floating elements out-of-normal flow; container divs only resize to normal flow content.

Solution

Put overflow:hidden on the parent div and don’t specify a height:

#parent { overflow: hidden }

Another way is to also float the parent div:

#parent { float: left; width: 100% }

Another way uses a clear element:

<div class="parent">
   <img class="floated_child" src="..." />
   <span class="clear"></span>
</div>

CSS

span.clear { clear: left; display: block; }
Container div with float elements inside was last modified: May 26th, 2015 by tabcom