4种元素居中的方式

98 阅读1分钟

flex

    .parent {
      height: 200px;
      width: 200px;
      display: flex;
      justify-content: center;
      align-items: center;
      border: 1px solid red;
    }

绝对定位

    .parent {
      height: 200px;
      width: 200px;
      position: relative;
      border: 1px solid red;
    }

    .son {
      height: 100px;
      width: 100px;
      position: absolute;
      background-color: aqua;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
    }

利用伪元素

    .parent {
      height: 200px;
      width: 200px;
      border: 1px solid forestgreen;   
      text-align: center; // 水平居中的关键属性
    }

    .son {
      height: 100px;
      width: 100px;
      background-color: aquamarine;
      display: inline-block;
      vertical-align: middle;
    }


        
    .parent::before {
        height: 100%; // 高度 100% 宽度 0
        width: 0;
        display: inline-block; // 内联块
        content: '';
        vertical-align: middle; // 内联块中线对齐
    }

利用 margin: auto

  .demo {
    height: 20px;
    width: 20px;
    background-color: blue;
    margin: auto;
  }
  /*
      demo 是块级元素,空间理应占满一行,只是你给了宽高20,所以呈现的大小是这样,但是
      实际上空间还是占满一行的,所以此时利用 margin: auto; 会分配剩余的空间,所以就水平
      居中了,因为块元素垂直方向上不占据空间,故而实现不了垂直居中,那应该怎么实现垂直居中呢?
  */
  .demo {
    height: 20px;
    width: 20px;
    background-color: blue;
    margin: auto;
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
  }
  /*
      因为设置了定位且 top left right bottom 都是0,所以元素就变成了占满整个空间的块,
      此时使用margin: auto;去分配剩余空间,自然就居中了;
  */