views:

32

answers:

1

So I have a small div for the border, and three divs inside (see image at end). Green is full size (minus padding etc); Blue should float left and have specific width; Red should float right and also have a specific width. However I'm messing something up. Both of the blue and red divs float outside the main div. What am I doing wrong here?

Here's my current code:

<div style="border: 2px solid black; width: 630px;">
  <div style="width:auto;">Lorem ipsum</div>
  <div style="width:150px; float:left;">This is the blue box</div>
  <div style="width:150px; float:right;">This is the red box</div>
</div>

Ideal Float

+3  A: 

Positioning of floats is funny. Basically, the main div is not taking into account the height of the floated elements when figuring out its own height. The easiest way to resolve this is to add a clearing element after the floated elements.

This fiddle should explain itself clearly: http://jsfiddle.net/QQxb3/2/

I think that the folks who commented on your post saying that it does work must have misunderstood what you mean by "main div", because specification, which Chrome does follow and IE follows in this particular instance, would place the floated elements outside of its parent div.

Steven Xu
Thanks, that was exactly the problem.
aslum
There would be no need to use a clearing div.Overflow:hidden with a hasLayout trigger for IE would suffice and is much neater.
RyanP13
RyanP13's comment is correct. See http://jsfiddle.net/QQxb3/5/. I never knew about that before and agree it is a much more satisfying solution than mine.
Steven Xu
@ Steven Xu - it was new to me too. Only found out about it as sometimes using overflow:auto on complex nested floats can create undesirable scrolling. Doesn't happen often but did on my last project.
RyanP13