元素水平垂直居中

若如初见. 提交于 2019-12-05 03:12:20
  1. flex布局,新版本

    //css
    body {
      display: flex;
      justify-content: center;
      align-items: center;
    }
    .box {
      background: red;
      width: 200px;
      height: 200px;
    }
    //html
    <body>
        <div class="box"></div>
    </body>
  2. flex布局,老版本

    //css
    body {
        display: -webkit-box;
        -webkit-box-pack: center;
        -webkit-box-align: center;    
    }
    .box {
        background: red;
        width: 200px;
        height: 200px;
    }
    //html
    <body>
        <div class="box"></div>
    </body>
  3. 容器position为absolute

    //css
    .box {
          background: red;
          width: 200px;
          height: 200px;
          position: absolute;
          left: 0;
          right: 0;
          top: 0;
          bottom: 0;
          margin: auto;
    }
    //或者
    .box {
          background: red;
          width: 200px;
          height: 200px;
          position: absolute;
          left: 50%;
          right: 50%;
          margin-top: -100px;
          margin-left: -100px;
    }
    //或者
    .box {
          background: red;
          width: 200px;
          height: 200px;
          position: absolute;
          left: 50%;
          right: 50%;
          transform: translate(-50%,-50%);
    }
    //html
    <body>
        <div class="box"></div>
    </body>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!