【CSS】如何实现垂直居中?

173 阅读1分钟

忠告:能不写 height 就千万别写 height。

  • 如果 .parent 的 height 不写,你只需要 padding: 10px 0; 就能将 .child 垂直居中;
  • 如果 .parent 的 height 写死了,就很难把 .child 居中,以下是垂直居中的方法。

一、table自带

table 表格的内容会自动垂直居中

二、div 装成 table

将CSS设置成 display:table

三、通过相对定位和绝对定位来实现

margin-top -50%

translate -50%

absolute margin auto

四、flex布局

flex

justify-content: center;
3align-items: center;