float元素负margin效果

·  阅读 109

代码:

HTML

**

  <body>
    <section>
      <div class="first"></div>
      <div class="active style="width: 200px"> some text</div>
    </section>
 </body>
复制代码

CSS

**

section > * {
        box-sizing: border-box;
        padding: 20px;
        float: left;
    }
    section{
        margin: 0;
        padding: 20px;
        overflow: hidden;
        background: beige;
    }
    .first{
        width: 100%;
        height: 120px;
        
    }
    .active{
        
        border: 1px solid;
        width: 200px;
        height: 120px;

            }
复制代码

.first和.active均向做浮动,box-sizing为border-box:

设置.active为负的margin-left:margin-left: -20px;因为与浮动方向相同,.active向左移动:

但 margin-left绝对值大于等于自身宽度时,.active会进入.first的区域,为什么呢??

margin-left:-200px;

2.PNG

margin-left: -100%;

3..PNG

W3C关于float的规则:

  • If the current box is left-floating, and there are any left-floating boxes generated by elements earlier in the source document, then for each such earlier box, either the left outer edge of the current box must be to the right of the right outer edge of the earlier box, or its top must be lower than the bottom of the earlier box.
    Analogous rules hold for right-floating boxes.

  • A floating box must be placed as high as possible

  • A left-floating box must be put as far to the left as possible, a right-floating box as far to the right as >possible. A higher position is preferred over one that is further to the left/right.

float box会向左或右移动直到它的edge碰到另一个float box的edge或它的containing blox edge。所以.active float box 会向上移动到.first float box的右边缘,margin-left绝对值大于其自身的宽度时,所以.active float box会向左移动到其containing box的左content edge。

分类:
前端
标签:
分类:
前端
标签:
收藏成功!
已添加到「」, 点击更改