Click to See Complete Forum and Search --> : understanding floats


gilyotina
05-02-2008, 09:19 AM
hi,

just when i thought i understood the concept of floated divs..

i have 2 divs inside my container div.
the first div, "article", is set to float:left.

the other div acts strange. when i set it to float:left, the width of the div is correctly 300px. However, i cannot make it horizontally centered (by using margin: 0 auto;). WHY CANT IT BE CENTERED?

when i remove the float:left from that second div ("sidebar"), its size changes to 150px. And still, it cannot be centered. WHY DOES THE SIZE CHANGE?

I attach 2 images of the page.

this is the relevant css code:

#container{
background-color: #FFFFFF;
width:750px;
margin:0 auto;
min-height:450px;
}

#article{
margin-top:20px;
padding-left:5px;
width:370px;
background-color:#CCFF66;
float:left;
}

#sidebar{
width:300px;
margin:20px auto;
padding:0;
background-color:#CCCC66;
}

tnx

Centauri
05-02-2008, 10:18 AM
When an element is floated, it is lifted up out of the document flow, and other elements can then slide behind it. The auto side margins will not centre it, as the whole purpose of the float is to move it to the left or right, depending on which direction it is floated. In your second example, the #sidebar div is still 300px wide and centred - centred within the container and partly hidden by the floated div sitting above it. The contents (the images) of #sidebar are shifted across to avoid the float (one of the important properties of floats to allow content to flow around them), but #sidebar itself is partially behind the float. Note that this behaviour is very different in IE6 due to its broken float model.

If you want #sidebar centred in the area to the right of the float, there are a couple of methods. If the container and divs widths are known and do not change, then you can calculate and apply the correct amount of left margin to sit #sidebar in the centre. If the width of #container is variable, then you could give #container a left padding equal to the width of the float, and give the float a negative left margin to pull it across into the padding area :#container{
background-color: #FFFFFF;
width:380px;
margin:0 auto;
padding: 0 0 0 370px;
min-height:450px;
}

#article{
margin-top:20px;
padding-left:5px;
width:370px;
background-color:#CCFF66;
float:left;
margin-left: -370px;
}

#sidebar{
width:300px;
margin:20px auto;
padding:0;
background-color:#CCCC66;
}

gilyotina
05-02-2008, 03:55 PM
since the sizes are fixed, i used the first method you offered. worked like charm, tnx!