How this float div is getting top margin when wrapper div has no border?

情到浓时终转凉″ 提交于 2019-12-12 17:22:23

问题


Please note that I am not asking about correcting the problem but instead I want to know how floated div is getting margin when wrapper div has 0px border set. But when wrapper div has 1px border set then floated div doesn't get margin but in both cases secondDiv gets top margin as intended.

Please note that I understand margin collapsing topic but what it has to do with setting border?

<div id="container">    
    <div id="firstDiv">FIRST Div inside CONTAINER</div>
    <div id="secondDiv">SECOND Div inside CONTAINER</div>
</div>


body{
    width: 780px;
    margin: 00px auto;
}
#container {
    border: 1px solid orange;   /* but when its set to 0px then floated div gets margin too*/
}
#firstDiv{         
    float:left;
}
#secondDiv{  
     margin: 14px;        
}

http://jsfiddle.net/dmpxw/

Now, if border of wrapper div is set to 0px then floated is pushed downward too. But I think shouldn't it stay there like in previous case?

http://jsfiddle.net/dmpxw/1/


回答1:


This is an interesting one.

When the container has a border, the margin of the second inner div runs from the border - i.e. the margin applies from the border onwards. This is because the border is the last item that applies before the margin measurement.

When the container does not have a border, the margin of the second inner div runs from the last item, which is now the body. So the margin is now OUTSIDE of the container, so the container is now actually further down the page - the first inner div has no margin, and is right at the top of the container - it is the container itself that has moved in the second case.

If you add a background color to your example, you can see that when you have a border the margin is inside the container, and when you have no border the margin is outside the container. View the example on JSFiddle.



来源:https://stackoverflow.com/questions/9330976/how-this-float-div-is-getting-top-margin-when-wrapper-div-has-no-border

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!