tags:

views:

40

answers:

3
+1  Q: 

html float problem

I have the following code:

<div "background-color:green">
    <div "float:left">something</div>
    <div "float:right:>something else</div>
<div>

Why does the background color not appear in this case? What needs to be done to make it appear {Code simplified for understanding , may not be in the approporiate syntax}

+1  A: 

A floated object is "lifted" from its containter. The bottom edge of the outer div doesn't stretch to its content anymore.

An option is to add an element with clear (clear takes a direction (either left, right, or both), and pushes itself below a float it would touch:

<div style="background-color: green">
    <div style="float: left">something</div>
    <div style="float: right">something else</div>
    <br style="clear: both;" />
<div>
Tordek
I would argue that it isn't 'lifted', but any container with only floated children will 'collapse'. Sorry to be nitpicky.
alex
Uhm, not so much, because if there is a 100px tall floated box, inside a div with containing something else (not floated), the box will escape its container.
Tordek
You are correct. But notice is I said '*only* floated children'.
alex
A: 

You need to write in the style attribute

<div style="background-color:green;">
    <div style="float:left;">something</div>
    <div style="float:right;">something else</div>
<div>
ChaosPandion
I assume he ommited it for simplicity.
Tordek
Never underestimate people...
alex
I actually hope I am wrong.
ChaosPandion
ommitted for simplicity folks..!! only the solution required! not the syntax :)
Ajay
+2  A: 

You need to clear the div. You can use clear: both on an element beneath, but I often find this is easier:

<div style="background-color:green; overflow: hidden;">
    <div style="float:left;">something</div>
    <div style="float:right;">something else</div>
<div>

Notice the overflow: hidden.

Of course, it only works where you don't require elements to leave their containing elements.

alex