float元素负margin效果

代码:

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:

margin.PNG

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

捕获.PNG

但 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。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容