zoukankan      html  css  js  c++  java
  • 绝对定位下margin的作用

    以前一直对绝对定位下的margin作用很模糊,今天细看一下

    不使用top,left,margin等

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>Document</title>
      <style>
        .container{
          position: relative;
          border: 1px solid blue;
           500px;
          height: 500px;
          margin: 100px auto;
        }
        .child{
          position: absolute;
           100px;
          border:1px solid red;
          height: 100px;
        }
        .before{
          display: inline-block;
           100px;
          height: 100px;
          border: 1px solid black;
        }
        
      </style>
    </head>
    <body>
      <div class="container">
        <span class="before">1212</span>
        <span class="child">22 </span>
      </div>
    </body>
    </html>
    


    可以看出,自然状态下,绝对定位元素参照标准流位置,紧邻before元素

    只定义left、top不使用margin

    .child{
          position: absolute;
           100px;
          border:1px solid red;
          height: 100px;
          top:10px;
          left: 10px;
        }
    


    可看出定位元素是相对于使用了定位的父级元素

    只使用margin

    .child{
          position: absolute;
           100px;
          border:1px solid red;
          height: 100px;
          margin-left: 10px;
        }
    


    可以看到它是根据未用position定位的before元素的边界进行margin定位的,对margin-top同样适用

    margin与left/top结合

    .child{
          position: absolute;
           100px;
          border:1px solid red;
          height: 100px;
          margin-left: 70px;
          left: 50px;
        }
    


    可以看出定位元素是相对于父级进行了定位的元素进行定位的,margin-left+left=120px,对margin-top同样适用

    总结

    1、只使用left等定位是按照上层相对定位(或绝对定位)的边界进行定位

    2、只使用margin相关属性定位时按照上层标准流(或浮动)块的边界进行定位

    3、当同时使用两者时则按照上层相对定位(或绝对定位)的边界进行定位,并且距离值为两者的相加值

    4、对于不使用left也没有margin的,自动按照上层标准流进行定位

    #con{  
        position:absolute;  
        left:50%;  
        760px;  
        margin-left:-380px;  
    }
    

    使用绝对定位与margin是有道理的

  • 相关阅读:
    Topic for paper reading
    Github
    APPIUM+Python+HTMLTestRunner(转)
    PyCharm 2016.3.2 汉化
    APPIUM 常用API(转)
    Python IDE PyCharm2016.3.2(转)
    APPIUM笔记
    将博客搬至CSDN
    碎碎念
    关于set或map的key使用自定义类型的问题
  • 原文地址:https://www.cnblogs.com/raind/p/10650615.html
Copyright © 2011-2022 走看看