individualtermite
individualtermite

Reputation: 3755

Float Creates Overlapping Divs

I have two divs (one inside of the other) and am running into a bit of a problem when I float the one inside to "left". The problem is that the outer div doesn't expand its height to fit the text inside of the inner div. Since this is probably pretty confusing, I'll try to explain it with some code.

HTML:

<body>
    <div id="div1">
        Inner Div:
        <div id="div2">Testing long content.</div>
    </div>
</body>

CSS:

#div2 {
    float: left;
    width: 10px;
}

I rather hope that when tested this actually shows my problem as I have not had a chance to test this. My real code has more properties which I will pose these if needed.

Upvotes: 13

Views: 33420

Answers (5)

Ryan McGrath
Ryan McGrath

Reputation: 2042

While the solutions above should work, I figure it's worth pointing out that there's one magical trick I haven't seen considered yet (in this thread).

Just float #div1 left. When you float the parent element, it'll automagically clear the child element - fairly useful, really. You could build an entire layout of floated stacks, and then have one final clear at the end, and it'd be fairly reliable.

Upvotes: 1

Michiel
Michiel

Reputation: 2634

Maybe handy to note that there is also the well know clearfix code from positioniseverything that is written specifically for this problem and is probably most robust and easiest to apply in any situation. The CSS looks as follows:

<style>
div.clearfix:after { content: "."; display: block; height: 0; clear: both; visibility: hidden; }
div.clearfix { display: inline-block; margin: 0 0 8px 0; }
/* Hides from IE-mac \*/
* html div.clearfix { height: 1%; }
div.clearfix { display: block; }
/* End hide from IE-mac */
</style>

In order to use it in your situation you would do the following:

<body>
<div id="div1" class="clearfix" >Inner Div:
<div id="div2">Testing long content.</div>
</div>
</body>

Upvotes: 5

Emily
Emily

Reputation: 10088

If you don't want to add additional markup to your html or add a width to your outer div, you can use:

#div1 {
    overflow:hidden;   /* clears float for most browsers */
    zoom:1;            /* clears float for IE6           */
    }

Upvotes: 8

Itay Moav -Malimovka
Itay Moav -Malimovka

Reputation: 53597

(The third time today :-) ) give the outer div overflow: hidden;
and width.

Upvotes: 2

Sampson
Sampson

Reputation: 268344

You need to use the clear-fix. Insert the following after your floated div, and within the containing div.

<div class="clear"></div>

And add the following style:

.clear { clear:both; }

Example:

<div class="container">
  <div class="floatedDiv">Hello World</div>
  <div class="clear"></div>
</div>

Upvotes: 36

Related Questions