zoukankan      html  css  js  c++  java
  • 水平垂直居中方法(包含flex新版本和旧版本)

    页面中有一个灰色的块:宽高各400px,块中还有一个小的div颜色为粉色:宽高各为200px,如何让这个粉色的块在灰色的块中水平垂直居中呢?

      <div class="wrap">
        <div class="box"></div>
      </div>
        *{
          padding:0;
          margin:0;
        }
        .wrap{
           400px;
          height:400px;
          background: grey;
        }
        .wrap .box{
           200px;
          height:200px;
          background: hotpink;
        }

    1.父相子绝,子: top:0; left:0; right:0 ;bottom:0; margin: auto;

        *{
          padding:0;
          margin:0;
        }
        .wrap{
           400px;
          height:400px;
          background: grey;

          position: relative;
        }
        .wrap .box{
           200px;
          height:200px;
          background: hotpink;

          position: absolute;
          top:0;
          left:0;
          right:0;
          bottom:0;
          margin: auto;
        }

     2.父相子绝,子:top:50%, left:50%, margin-left:-100px; margin-top: -100px;(这个100px就是子元素的宽高的一半)

    
    
       .wrap{
           400px;
          height:400px;
          background: grey;

          position: relative;
        }
        .wrap .box{
           200px;
          height:200px;
          background: hotpink;

          position: absolute;
          top:50%;
          left:50%;
          margin-left: -100px;
          margin-top: -100px;
        }
     

    3.父相子绝,子: top:50%;  left:50%; transform:translate(-50%,-50%)

        .wrap{
           400px;
          height:400px;
          background: grey;
    
          position: relative;
        }
        .wrap .box{
           200px;
          height:200px;
          background: hotpink;
    
          position: absolute;
          top:50%;
          left:50%;
          transform:translate(-50%,-50%)
        }

    4.flex新版本:父级: display: flex;  justify-content: center; align-items: center;

        .wrap{
           400px;
          height:400px;
          background: grey;
    
          display: flex;
          justify-content: center;
          align-items: center;
        }
        .wrap .box{
           200px;
          height:200px;
          background: hotpink;
        }

    5.flex旧版本:display: -webkit-box; -webkit-box-pack: center; -webkit-box-align: center;

      .wrap{
           400px;
          height:400px;
          background: grey;
    
          display: -webkit-box;
          -webkit-box-pack: center;
          -webkit-box-align: center;
        }
        .wrap .box{
           200px;
          height:200px;
          background: hotpink;
        }

    以上方法亲测有效,

  • 相关阅读:
    hdu 6049 Sdjpx Is Happy
    L2-012. 关于堆的判断
    L2-010. 排座位
    L2-009. 抢红包
    L2-007. 家庭房产
    L2-008. 最长对称子串
    L2-011. 玩转二叉树
    l2-006 树的遍历
    l2-005
    l1-20 帅到没朋友
  • 原文地址:https://www.cnblogs.com/yaya-003/p/12072212.html
Copyright © 2011-2022 走看看