Tuesday, July 07, 2009

Clearing a float

I found out a cool way to clear a floated element the other day without having to use a clearing div/break or whatever your favorite method of clearing is. In fact you don’t have to add any extraneous html to achieve the clear. Give it a shot yourself. Here is the key ...
The CSS
.box {
    border: 1px solid #999999;
}

#header {
    width: 217px;
    margin: 0px 0px 5px 0px;
    padding: 5px;
}

#container {
    overflow: hidden; /*This is the magic.  It will clear the footer without needing a clearing div*/
}

#left {
    width: 100px;
    float: left;
    margin: 0px 0px 5px 0px;
    padding: 5px;
}

#right {
    width: 100px;
    float: left;
    margin: 0px 0px 5px 5px;
    padding: 5px;
}

#footer {
    width: 217px;
    padding: 5px;
}
The HTML
<html>
    <body>
        <div id="header" class="box">
            Header
        </div>
        <div id="container">
            <div id="left" class="box">
                Left
            </div>
            <div id ="right" class="box">
                Right
            </div>
        </div>
        <div id="footer" class="box">
            Footer
        </div>
    </body>
</html>

No comments: