水平垂直居中

22 阅读1分钟

🧩 一、Flex 布局(最推荐 ✅)

.parent {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center;     /* 垂直居中 */
  height: 300px; /* 必须有高度 */
  background: #f2f2f2;
}
.child {
  width: 100px;
  height: 100px;
  background: tomato;
}

优点

  • 写法简洁;
  • 响应式友好;
  • 现代浏览器全面支持。

🧩 二、Grid 布局

.parent {
  display: grid;
  place-items: center; /* 等价于 align-items + justify-items */
  height: 300px;
  background: #f2f2f2;
}
.child {
  width: 100px;
  height: 100px;
  background: tomato;
}

优点

  • 写法更简洁;
  • 也适合复杂布局;
  • flex 类似但语义更强。

🧩 三、定位 + transform

.parent {
  position: relative;
  height: 300px;
  background: #f2f2f2;
}
.child {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 100px;
  height: 100px;
  background: tomato;
}

优点:兼容性好(IE 也支持)
⚠️ 注意transform 是相对于自身的偏移。