Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Float - The content stays in the default stack position

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;
}
like image 529
Jinto Avatar asked Dec 20 '22 15:12

Jinto


2 Answers

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).

like image 89
BoltClock Avatar answered Jan 20 '23 14:01

BoltClock


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/

like image 24
sreekarun Avatar answered Jan 20 '23 16:01

sreekarun