美文网首页
float元素负margin效果

float元素负margin效果

作者: xingyakong | 来源:发表于2017-02-19 15:39 被阅读0次

    代码:

    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。

    相关文章

      网友评论

          本文标题:float元素负margin效果

          本文链接:https://www.haomeiwen.com/subject/ujjjwttx.html