Part 6. Floats

Floated elements inside a container

Below are examples of floated items inside a container. The floated items are small yellow-green boxes. The containers are grey boxes with darker grey borders.

Floated elements are taken out of normal flow, so their containers cannot determine their height. The grey containers will stretch to fit content inside them - but only content that is in normal flow. The containers will ignore the height of the floated items.

Example 1

If the content inside the container is long enough, the floated item may appear to sit correctly inside the container.

Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Duis autem vel eum iriure dolor in hendrerit in vulputate velit esse molestie.

Example 2

If the content inside the container is very short, the floated item may poke out the bottom of the container.

Text here

Example 3

If a container has no content inside, it has no height so it should not render the grey background color at all. If there is only a floated item inside, then only this item will render. As you can see, the container will not render around the floated item.

Solution 1 - an extra clearing <div>

You can force the container to clear floated items inside. The container below has short content, but there is also a clearing element inside to push the container below the floated item. In this case, a <div> element is used, styled with "clear: both".

Text here

Solution 2 - float the parent container

You can float the parent container as well as the floated item inside. The parent container will then wrap around the floated item.

Text here

Solution 3 - overflow: auto

You can set the parent container to "overflow: auto". This allows the parent container to spread to fit floated content inside.

Text here

External resources