• 绝对定位下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是有道理的

  • 相关阅读:
    Confluence未授权模板注入/代码执行(CVE-2019-3396)
    Python实现批量处理扫描特定目录
    windows10 缺失 msvcp140.dll 解决办法
    nessus 故障处理
    python 处理json数据
    python 实现两个文本文件内容去重
    python3 实现多域名批量访问特定目录(一)
    python 简单的实现文件内容去重
    python 实现爬取网站下所有URL
    php强大的filter过滤用户输入
  • 原文地址:https://www.cnblogs.com/raind/p/10650615.html
Copyright © 2020-2023  润新知