2
votes

I have 3 divs that stack on top of one another. All have the same width and height, e.g. 500px x 500px.

Top div float right. 2nd one margin-left and margin-right are set auto. 3rd one float left. All have the same margin top of 50px and all clear:both.

Of course there's a wrapper div wrapping the 3 divs and width 100%.

Question: Why is that the 2nd div margin top doesn't push that 50px margin but overlaps the top div?

I have tried looking for answer in similar questions here but none are what I'm looking for.

Here's a sample of the html and css that I'm doing.

<!DOCTYPE html>
<html>
<head>
<style>
.wrapper{width:100%; clear:both;}
.haha{width:500px; height:500px; margin-top:50px; clear:both;}
.haha.right{float:right;}
.haha.left{float:left}
.haha.center{margin-left:auto; margin-right:auto;}
</style>
</head>
<body>
<div class="wrapper">
<div class="haha right"><img src="wahaha.jpg"></div>
<div class="haha center"><img src="wahaha.jpg"></div>
<div class="haha left"><img src="wahaha.jpg"></div>
</div>
</body>
</html>

JS Fiddle here http://jsfiddle.net/dhS2x/3/

3
Due to the fact that the box above is floating and the center box is not floatingHuangism
Yes, I know the box above is float. Any solution for this? Thanks.Archampion
See the solution below, hopefully it works for your scenario!Sam Hood
@Archampion there is already an answerHuangism
Can you create a jsfiddle to better illustrate the problemElmer

3 Answers

1
votes

You can get the desired effect by adding the following to the .haha.right class:

margin-bottom:50px;

As for why this happens, it's something to do with the fact that the middle div is not being floated, whereas the others are.

1
votes

I know this is dirty. But you can achive this by adding separate clearing divs after each .haha div like below.

<div class="wrapper">
<div class="haha right"><img src="wahaha.jpg"></div>
    <div class="clear"></div>
<div class="haha center"><img src="wahaha.jpg"></div>
    <div class="clear"></div>
<div class="haha left"><img src="wahaha.jpg"></div>
    <div class="clear"></div>
</div>

And CSS

.clear{clear:both;}

JS-Fiddle http://jsfiddle.net/Q4u6P/1/

1
votes

According to W3C: http://www.w3.org/TR/CSS2/visuren.html#floats

Since a float is not in the flow, non-positioned block boxes created before and after the float box flow vertically as if the float did not exist.

If my interpretation is right, the top margin for the second div is there but is set against the edge of the wrapper container or any non-floated elements above it, this is due to floated element being considered taken out of the normal flow of the document.

if you want the vertical gap between div1 and div2, set the margin-bottom on div1 instead.

#div1{
    float: right; 
    margin-bottom: 50px;/*set margin here instead*/
}

JSFiddle: http://jsfiddle.net/luongatoolz/DxDmp/1/