CSS floats: container does not stretch to fit floated contents

Read Time:1 Minute, 19 Second

Original Article: http://www.mikepadgett.com/technology/technical/alternative-to-the-pie-clearfix-hack/

Here’s a quick resolution to an almost ungooglable problem.”

This article was formerly titled “Alternative to the PIE clearfix hack” but has since been rewritten.

Getting this problem?

Nested div float problems

Example:

Left
Left
Left
Left
Right
Right
Right
Right


<div style="background: red; padding: 2%; border: 1px solid #000;">
<div style="border: 1px solid #000000; background: #e2e2e2; float: left; width: 45%;">Left<br />Left<br />Left<br />Left</div>
<div style="border: 1px solid #000000; background: #e2e2e2; float: right; width: 45%;">Right<br />Right<br />Right<br /></div>
</div>

There are generally two ways of dealing with this and you shouldn’t usually need to hack it.

Hack-free approach

Normally, you can apply something like the following to the outer div:

height: 1%; overflow: hidden;

In most modern browsers, the container will now stretch to fit the floated contents.

Left
Left
Left
Left
Right
Right
Right
Right


<div style="background: red; padding: 2%; border: 1px solid #000; height: 1%; overflow: hidden;">
<div style="border: 1px solid #000000; background: #e2e2e2; float: left; width: 45%;">Left<br />Left<br />Left<br />Left</div>
<div style="border: 1px solid #000000; background: #e2e2e2; float: right; width: 45%;">Right<br />Right<br />Right<br /></div>
</div>

 

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.