Monday, August 10, 2009

Placing Two DIVs Side-by-Side using CSS

There is a little CSS trick needed when placing two HTML elements or DIVs side-by-side in order to prevent the two elements from jumping out of the containing DIV. In this simple demonstration there is an 'outer' DIV containing a 'header' DIV containing a 'title' DIV and a 'search' FORM. The FORM could just as well be a DIV for this to work. The title and search are forced left and right using 'float:left' and 'float:right' respectively. The trick is to add a third DIV after the search FORM inside the header DIV with a CSS 'clear:both' styling: <div style="clear:both;"></div>.

Before:



After:


HTML & CSS:


<html>
<head>
<style type="text/css">

#outer {
    width:600px;
    margin:0 auto;
    background:#BBBBBB;
    text-transform:uppercase;
    padding:10px;
}

#header {
    background:#0044FF;
    padding:5px 10px;
}

#title{
    background:#FF2244;
    padding:10px;
    float:left;
}

#search{
    background:#22CC22;
    padding:10px;
    float:right;
}

</style>
<body>
<div id='outer'>
    <div id='header'>
        <div id='title'>
            <p>Website Title</p>
        </div>
        <form id='search' method="get">
            <input type="text" name="searchText" />
            <input type="submit" value="Search" />
        </form> 
        <div style="clear:both;"></div>
    </div>
</div>
</body>
</html>


Piece of Cake!!

1 comment:

emran Talukder said...

thank you sooooo much! this is great tip! i was stuck for a whole hour on css formatting!!!! div is a must!
take a look at my site. 1 down, more to go...