前端基础——不知宽高如何居中

假设有两个盒子,不知道子盒子的宽高

  <div class="container">
    <div class="box"></div>
  </div>

要实现的效果如下:

第一种方法:

    .container {
      display: flex;
      justify-content: center;
      align-items: center;
    }

第二种:

    .container {
      position: relative;
    }

    .box {
      position: absolute;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
    }

第三种:

    .container {
      position: relative;
    }

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

第四种:

    .container {
      display: table-cell;
      text-align: center;
      vertical-align: middle;
    }

    .box {
      display: inline-block;
    }

第四种方法会导致父元素四个方向上的margin失效。

猜你喜欢

转载自blog.csdn.net/qq_42303885/article/details/85346047
今日推荐