一个不定宽高的元素如何在父元素中垂直水平居中

256 阅读1分钟

1.position方法

  • position+margin
.target {
   position: absolute;
   margin: auto;
   top: 0;
   left: 0;
   bottom: 0;
   right: 0;
}
  • position+transform
.target {
   position: absolute;
   top: 50%;
   left: 50%;
   transform: translate(-50%,-50%);
}

2.display方法

  • table+vertical-align+text-align
.target {
   display: table-cell;
   text-align: center;
   vertical-align: middle;
}

3.flex布局

  • align-items+justify-content
.target {
   display: flex;
   justify-content: center;
   align-items: center;
}

4.grid布局

  • place-content
.target {
   display: grid;
   place-content: center;
}