I'm currently trying to create a two column layout where the left column is floated and the right column restrains the float by forming a new block formatting context. That works. Later, I try to put some visible space between the left column and the content of right column. If I set left padding on the right column, it works. I also try to replace the left padding with left margin on the right column, and think they would have the same effect. However, to my surprise, the left margin is not working at all
I reproduce the problem with the following code. Notice that the example in the middle, setting the left margin on the right column does not really push it away from the left column
* {
margin: 0;
padding: 0;
}
.container {
height: 50px;
line-height: 50px;
width: 500px;
}
.container + .container {
margin-top: 20px
}
.left {
float: left;
width: 150px;
height: 100%;
background: orange;
text-align: center;
}
.right {
overflow: auto;
background: skyblue;
height: 100%;
}
.with-padding {
padding-left: 30px;
}
.with-margin {
margin-left: 30px;
}
<div class="container">
<div class="left">left column, floated</div>
<div class="right with-padding">
<p>left padding works</p>
</div>
</div>
<div class="container">
<div class="left">left column, floated</div>
<div class="right with-margin">
<p>left margin dost not work</p>
</div>
</div>
<div class="container">
<div class="left">left column, floated</div>
<div class="right">
<div class="with-margin">
<p>left margin works on the wrapper div</p>
</div>
</div>
</div>
I did search for this topic on the internet but don't find too much relevant information. I suspect this might be related to the concept of block formatting context (BFC). If I understand correctly, margin represents distance between the target box's outer edge and containing BFC's inner border.
If we set margin on a box which itself forms its own BFC, then margin shouldn't work? So in the third example, I place the text into an extra wrapper and set margin on that wrapper, and it looks like left margin work again. However, this is just my guess.