美文网首页
fixed absolute 居中定位的两种方法

fixed absolute 居中定位的两种方法

作者: 前端勾魂师 | 来源:发表于2020-09-04 10:28 被阅读0次

    一、使用transform进行居中

    html部分

    <div class="contain">
        <div class="center-box"></div>
    </div>
    

    上下左右居中

    .contain{
      position: relative;
      width: 100%;
      height: 100vh;
    }
    
    .center-box{
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 500px;
      height: 500px;
     background-color: #FF0000;
    }
    

    左右居中

    .contain{
      position: relative;
      width: 100%;
      height: 100vh;
    }
    
    .center-box{
      position: absolute;
      top: 0;
      left: 50%;
      transform: translate(-50%, 0);
      width: 500px;
      height: 500px;
     background-color: #FF0000;
    }
    

    上下居中

    .contain{
      position: relative;
      width: 100%;
      height: 100vh;
    }
    
    .center-box{
      position: absolute;
      top: 50%;
      left: 0;
      transform: translate(0, 50%);
      width: 500px;
      height: 500px;
     background-color: #FF0000;
    }
    

    二、使用margin进行居中(利用margin负值进行定位)

    上下左右居中

    .contain{
      position: relative;
      width: 100%;
      height: 100vh;
    }
    
    .center-box{
      position: absolute;
      top: 50%;
      left: 50%;
      margin-left: -250px;
      margin-top: -250px;
     /* 负数为盒子的一半 */
      width: 500px;
      height: 500px;
     background-color: #FF0000;
    }
    

    三、fixed用法同上(效果图)

    居中.png

    相关文章

      网友评论

          本文标题:fixed absolute 居中定位的两种方法

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