1. 程式人生 > 其它 >css 常用垂直居中

css 常用垂直居中

1. grid

 <style>
    .parent {
      display: grid;
      place-items: center;
      /* 等同align-items: center;justify-items: center;*/
      width: 300px;
      height: 300px;
      border: 1px solid #ccc;
    }
    .son {
      width: 50px;
      height: 50px;
      background: #f50;
    }
  </style>
  <div class="parent">
    <div class="son"></div>
  </div>

2.flex

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

3.flex+auto

 .parent {
      display: flex;
      width: 300px;
      height: 300px;
      border: 1px solid #ccc;
    }

    .son {
      margin: auto;
    }

4.table-cell

.son {
      width: 50px;
      height: 50px;
      background: #f50;
    }

    .parent {
      display: table-cell;
      text-align: center;
      vertical-align: middle;
      width: 300px;
      height: 300px;
      border: 1px solid #ccc;
    }

    .son {
      display: inline-block;
    }

5.absolute+transform

 .son {
      width: 50px;
      height: 50px;
      background: #f50;
    }

    .parent {
      width: 300px;
      height: 300px;
      border: 1px solid #ccc;
    }

    .parent {
      position: relative;
    }

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

6.absolute+margin:auto

 .son {
      width: 50px;
      height: 50px;
      background: #f50;
    }

    .parent {
      width: 300px;
      height: 300px;
      border: 1px solid #ccc;
    }

    .parent {
      position: relative;
    }

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