left margin not working on overflow:auto element following the float

Viewed 50

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.

1 Answers

The critical point here is that

The border box of ... an element in the normal flow that establishes a new block formatting context (such as an element with overflow other than visible) must not overlap the margin box of any floats ...

CSS 2.2 Section 9.5 Floats

So the margin, which lies outside the border box, of such a BFC can (and in your second case does) overlap with the float, but padding, which lies inside the border box, cannot.

Related