07 February 2010

Clearing nested CSS floats

Here's a XHTML/CSS technique to ensure you only clear the desired floats and get the right background areas for your DIV.

The code examples are here: http://www.phdcc.com/CSS_ClearingFloats.htm - look at the source code for full details.

My starting point is to have a DIV set with floats left and right. Within the middle unfloated DIV, I have another DIV set with floats and right. I want to clear just the middle floats, not the outer ones.

The crucial trick is to add CSS style 'overflow:hidden' to create a Block Formatting Context. Any CSS style 'clear:both' then only applies to the 'nearest'/current Block Formatting Context.

An associated problem was the fact that the background of the middle unfloated DIV goes wide to the border of the current Block Formatting Context. Adding CSS style 'overflow:hidden' to create a new context constrains the background to the expected area.

Using 'overflow:hidden' feels slightly naff: shouldn't there be an explicit CSS style to define a Block Formatting Context, instead of using something that does this as a side effect? Also, you may be concerned about what overflow is being hidden - as long as you have the default width:auto and/or height:auto set, you will not be hiding anything.


Anonymous said...

THANK YOU for this! Great explanation and saved me hours of time.

Anonymous said...

thanks from 2014

Anonymous said...

Thank you very much. I spent half a day trying to come up with a work around for this problem before finding your blog.

Anonymous said...

Thanks! :)