Why margin-left of a Block Formatting Context element cannot get a same result as margin-right of a float element?

前端 未结 2 1698
小鲜肉
小鲜肉 2020-12-19 15:16

Here is my code:



        
相关标签:
2条回答
  • 2020-12-19 15:40

    The MDN doc says :

    when you float the element to left the elements comes after taken out of the normal flow of the document (though still remaining part of it). It is shifted to the left, or right, until it touches the edge of its containing box, or another floated element.

    so if the right element have width of 100px

    the floated element comes after it will not take any action if you give it margin lower than 100px e.g 20px because it already far enough from this point but if you give it 200px it will take action

    .wrapper {
      border: 1px dashed red;
      overflow: auto;
      /*clear floating*/
    }
    
    .left {
      width: 120px;
      border: 5px solid #ffffd;
      float: left;
      margin-right: 20px;
    }
    .wrapper:after {
      content: "";
      display: table;
      clear: both;
    }
    
    .right {
      border: 5px solid #ffffd;
      overflow: auto;
      /*make div.right become a new BFC*/
      margin-left:200px;                                                                     
    0 讨论(0)
  • 2020-12-19 15:44

    The relevant part of the spec is https://www.w3.org/TR/CSS22/visuren.html#bfc-next-to-float which says:

    The border box of a table, a block-level replaced element, or 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 in the same block formatting context as the element itself. If necessary, implementations should clear the said element by placing it below any preceding floats, but may place it adjacent to such floats if there is sufficient space. They may even make the border box of said element narrower than defined by section 10.3.3. CSS2 does not define when a UA may put said element next to the float or by how much said element may become narrower.

    Which gives browsers a bit of latitude in what they actually do here, but the point is, if they place the BFC next to the float, the Border Box of the BFC must not overlap the Margin Box of the float. So changing the size of the margin on the BFC won't impact on that constraint, but changing the size of the margin on the float will.

    0 讨论(0)
提交回复
热议问题