Coder 2
Coder 2

Reputation: 4881

Two divs floated left next to each other the second must take up the rest of the line

HI, can someone please help me with this. I have:

<html>
<body>
<div style="width=100%">
    <div style="float:left; background-color:Red; height:100px">Red</div>
    <div style="background-color:Green;">Green</div>
    <div style="background-color:Yellow;">Yellow</div>
</div>
</body>
</html>

Which gives me exactly what I want, a Red div on the left with a Green div beside it taking up the rest of the width with a Yellow div beside the Red but below the Green div.

However the parent div actually has to also float left ie.

<html>
    <body>
         <div style="width=100%; float:left">
              <div style="float:left; background-color:Red; height:100px">Red</div>
              <div style="background-color:Green;">Green</div>
              <div style="background-color:Yellow;">Yellow</div>
         </div>
    </body>
</html>

This breaks it. Is there a way to get it working again with the parent div float left?

Upvotes: 1

Views: 5032

Answers (3)

Matt Mitchell
Matt Mitchell

Reputation: 41823

You wrote width=100% instead of width:100% - fixed example:

<html>
    <body>
         <div style="float:left;width:100%;">
              <div style="float:left; background-color:Red; height:100px;">Red</div>
              <div style="background-color:Green;">Green</div>
              <div style="background-color:Yellow;">Yellow</div>
         </div>
    </body>
</html>

The reason it worked originally, is that there is an implicit width of 100% on block elements, but you made your div an inline element (of sorts) by adding the float (such that the width of the div reverted back to the content's width, just as your Red div works).

Your width=100% was always ignored, so by putting the width:100% as it should be, you are specifying a width for the element and all is well.

Example: http://jsfiddle.net/hwb4w/

Upvotes: 0

robx
robx

Reputation: 3123

if you float the parent div, in order to keep them all in the parent container, you must also float them all. Those inside without float will fall out.

Edit: Note though that once you float them, width:100% means nothing anymore since the element don't know what to align 100% width with. Might have to give it some fixed width, or use JQuery to get width from document.

http://jsfiddle.net/robx/cpFUV/

Upvotes: 2

Thomas Shields
Thomas Shields

Reputation: 8942

It breaks it because a div is normally set to have a width of 100% it's parent container. Setting float:left makes the width set to the content's width. Set a width on your parent container and it should fix it.

Upvotes: 1

Related Questions