Home | SkillForge Blog | CSS Clearfix: Three Lines and a Breakdown

CSS Clearfix: Three Lines and a Breakdown

CSS, Web Design

Occasionally the learning curve in web design can be gentle. Other times it’s a sharp right angle and once in a while it’s just a nasty hair-pin curve. How you perceive these curves is just that, your perception. You know, this morning you feel as sharp as a tack and late in the afternoon you feel as dull as a butter knife.

Clearing floated elements has been one of those butter knife curves for me. True confession time…it hasn’t been a gentle or sharp curve, it’s a I know it works so I haven’t devoted brain time to understand it curve. Was that out load? They say confession is good for the soul.

Let’s break it down and see why it’s necessary and why it works.

basic-code

The code above results in the page below. Two nested containers inside an outer wrapper. That outer wrapper should be 100% of the pages width, as tall as whatever it contains (height: auto), and it has a light gray background color.

Inside the wrapper are two boxes that should each be 30% of the wrappers width, 100 pixels in height, and have a phthalo green background color which is 70% opaque.

floated-divs

But there is a slight problem, the background color of the wrapper is missing. That’s because floated elements don’t follow the pages normal flow rule. They are removed to float left or float right which means the wrapper now believes it has no content. The height: auto of nothing is…nothing. No content, no background color.

The fix, or clearfix as it has been designated comes to the rescue. Three simple statements that make things right based on a pseudo class, a display property, and the clear property.

CSS has introduced many pseudo (false) classes in its last two versions :before and :after being included in that list. Both of these pseudo classes are useless without its content value. What are we inserting before or after? In the typical clearfix code the content can either be an empty string or a single space. We just need some content in our wrapper that is not floated and it will be placed after any existing content.

That leaves our display: block property-value pair. Using the rules established in the Block Formatting Context by the W3C block formatted elements will contain their floated children and cannot extend past the bottom edge of the block.

The code below shows our added clearfix and below it is the resulting web page showing the missing background color of the wrapper.

css-with-clearfix

floated-divs-with-clearfix