CSS—一个盒子实现水平垂直居中

148 阅读1分钟

一、定位

  • 子元素设置为绝对定位,top和left设置成50%
  • transform属性中的translate设置为-50%, -50%

二、flex布局

父项必须要有高度

三、绝对定位+负外边距

  • 子元素设置为绝对定位,top和left设置程50%
  • margin-top、margin-left设置成自身高宽的-50%
  • 注:对没有宽高的元素不适用

四、绝对定位+margin:auto

  • 子元素设置为绝对定位,top、left、bottom、right设置为0;
  • margin: auto