元素水平垂直居中

  • 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>
  • 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>
  • 容器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>
    發表評論
    所有評論
    還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
    相關文章