面试官:水平垂直居中方案给我三种以上

66 阅读1分钟

不知宽高的父子盒子,子盒子在父盒子中水平垂直居中

  1. 使用Flexbox布局:
.parent { 
    display: flex; 
    justify-content: center; 
    align-items: center;
    }

image.png

  1. 使用绝对定位和transform属性:
.parent {
  position: relative;
}

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

  1. 使用表格布局:
.parent {
  display: table;
  width: 100%;
  height: 100%;
}

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

  1. 使用网格布局:
.parent {
  display: grid;
  place-items: center;
}

.child {
  justify-self: center;
  align-self: center;
}