css: box around floating elements

by prettyscripts on 2010-09-20 16:25

csshtml

a common problem with when trying to box 2 floating elements, you see a zero-height box align to the top of the floating element.

eg, we have the following layout:

Code:

<div class="container">
    <div class="left">left column</div>
    <div class="right>right column</div>
</div>

and the following css:

CSS:

.container { border: 1px solid #000; }
.left { width: 48%; float: left; }
.right { width: 48%; float: right; }

usually the problem can be easily fixed by adding an element clearing both immediately after the container block. so the html code now looks like:

Code:

<div class="container">
    <div class="left">left column</div>
    <div class="right>right column</div>
</div>
<div style="clear: both;"></div>

note extra coded added at line 5.

i don't usually box the elements, so i usually don't remember to add this clear element after the container. however if i suddenly decided to change the site layout and want to add border or background color, the site looks awful! then there are countless effort trying to change the html code.

recently i found a solution that can be easily fixed with modifying css of the container by adding width and overflow properties:

CSS:

.container {
    width: 100%; overflow: hidden; /* add this! */
}

note for IE (6?) - 'width: 100%;' is a must. without it, the boxes will float everywhere, tested with IE6. box elements still show up correctly in firefox with or without specifying the width.