I have two divs in the page with same width and height.
if I give float: left to the first div, the second div goes up (which is fine because the floated element is taken out of the normal document flow)
But, why the content of the div still shows in the default stack position?
JsFiddle is given below
http://jsfiddle.net/xR9Rd/2/
<div class="box0">Box 0</div>
<div class="box1">Box1</div>
.box0 {
width: 100px;
height: 100px;
background-color: brown;
float: left;
}
.box1 {
width: 100px;
height: 100px;
background-color: red;
}
The width of each box is 100 pixels. When you float one over the other, there is no more horizontal space left in the second box for its content because it's completely occupied by the float, so the content has to wrap to the next line (and overflow the 100-pixel height in that process).
If you make the second box wider, the content will appear next to the float:
.box1 {
width: 150px;
height: 100px;
background-color: red;
}
The content will never appear behind the float, however, because inline content will always wrap around floats (otherwise, floating won't be very useful).
When you float an element to left, it is taken out of the flow, the next element is laid out as if the first one did not exist. Then the floated element is placed. the textual content is given a special treatment such that the text starts flowing around the floated element.
In the above example, the first div was taken out of flow and the second div was placed ( still has the block context and starts from extreme left ) as if no other element existed. Then the floated div is placed. Since both has same size, there is an overlap. Then the text float mechanism kicks in and try to place the text around the floated div. The text container ( box1 ) does not have any space after the floated div ( both are overlapping ) it is naturally pushed down. one way to see it aligned to the box is to increase the second box width, so that the text gets contained.
Other option is to add margin-left to the second div so that the second div starts at an offset from the floated div and there is space for the content to align it self around the first div. See the example fiddle
.box1 {
width: 100px;
height: 100px;
background-color: red;
margin-left: 100px;
}
http://jsfiddle.net/sreekarun/xR9Rd/8/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With