Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop <div>s from moving into each other with float defined?

Tags:

html

css

Very straightforward CSS question that I haven't been able to find the answer to so far:

I'm trying to lay out a page with two div's side-by-side in one row (using float:left; and float:right;) and then one div below them. The problem is that if the top row (defined as a div itself) is so wide that the space between the two divs can accomodate the bottom div, the bottom div moves up into the top row creating the appearance of a single row of three divs. I don't know if that's clear or not, but here's the code:

<div id="top div" style="width:400px;">
<div style="float:left;"><img src="images/xlab.jpg" width="100px" height="200px" /></div>
<div style="float:right;"><img src="images/ucbseal.jpg" width="100px" height="250px" /></div>
</div>

<div id="bottom div"><img src="images/xlab.jpg" width="200px" height="200px" /></div>

So, as above, since the top div has a 200px gap in between its left and right child elements, the image in the bottom div slides up between them. If I make the top div's width 399px that doesn't happen. I tried using the CSS "clear" property but that didn't solve the problem. I've always just worked my way around this seemingly-odd behavior in a sloppy way but want to find a better practice.

Any help or direction is greatly appreciated!

like image 231
Eric Avatar asked Feb 03 '10 19:02

Eric


2 Answers

Use overflow:auto on the first div

<div id="top div" style="width:400px;overflow:auto;">
<div style="float:left;"><img src="images/xlab.jpg" width="100px" height="200px" /></div>
<div style="float:right;"><img src="images/ucbseal.jpg" width="100px" height="250px" /></div>
</div>

<div id="bottom div"><img src="images/xlab.jpg" width="200px" height="200px" /></div>

it will cause the container div to expand to the contents of its children and so the following div will maintain its location..

like image 64
Gabriele Petrioli Avatar answered Nov 16 '22 00:11

Gabriele Petrioli


Try the 'clear' attribute on a new div:

<div id="top_div" style="width:400px;"> 
<div style="float:left;"><img src="images/xlab.jpg" width="100px" height="200px" /></div> 
<div style="float:right;"><img src="images/ucbseal.jpg" width="100px" height="250px" /></div> 
<div style="clear: both;" />
</div> 

<div id="bottom_div"><img src="images/xlab.jpg" width="200px" height="200px" /></div>
like image 41
mnemosyn Avatar answered Nov 15 '22 22:11

mnemosyn