【前端 | CSS系列】—— 第1篇:如何实现水平垂直居中对齐?

五种方法实现水平垂直居中对齐

  • [1. 使用【Flex 布局】](#1. 使用【Flex 布局】)
  • [2. 使用【Grid 布局】](#2. 使用【Grid 布局】)
  • [3. 使用【Table 布局】](#3. 使用【Table 布局】)
  • [4. 使用【绝对定位】+ 【transform 属性】](#4. 使用【绝对定位】+ 【transform 属性】)
  • [5. 使用【绝对定位】+ 【margin 属性】 ------(仅适用于:已知元素宽高)](#5. 使用【绝对定位】+ 【margin 属性】 ——(仅适用于:已知元素宽高))

1. 使用【Flex 布局】

css 复制代码
.container {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
}

2. 使用【Grid 布局】

css 复制代码
.container {
  display: grid;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
}

3. 使用【Table 布局】

css 复制代码
.container {
  display: table;
}
.child {
  display: table-cell;
  text-align: center; /* 水平居中 */
  vertical-align: middle; /* 垂直居中 */
}

4. 使用【绝对定位】+ 【transform 属性】

css 复制代码
.container {
  position: relative;
}
.child {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

5. 使用【绝对定位】+ 【margin 属性】 ------(仅适用于:已知元素宽高)

css 复制代码
.container {
  position: relative;
}
.child {
  position: absolute;
  top: 50%;
  left: 50%;
  margin: -50px 0 0 -50px; /* 其中50px是元素宽高的一半 */
}

单纯的元素左右居中 对齐:
块级元素 可以使用 magrin: 0 auto;
非块级元素 使用 text-align: center;

相关推荐
m0_7190841115 分钟前
React笔记张天禹
前端·笔记·react.js
Ziky学习记录29 分钟前
从零到实战:React Router 学习与总结
前端·学习·react.js
wuhen_n35 分钟前
JavaScript链表与双向链表实现:理解数组与链表的差异
前端·javascript
wuhen_n38 分钟前
JavaScript数据结构深度解析:栈、队列与树的实现与应用
前端·javascript
狗哥哥1 小时前
微前端路由设计方案 & 子应用管理保活
前端·架构
前端大卫2 小时前
Vue3 + Element-Plus 自定义虚拟表格滚动实现方案【附源码】
前端
却尘2 小时前
Next.js 请求最佳实践 - vercel 2026一月发布指南
前端·react.js·next.js
ccnocare2 小时前
浅浅看一下设计模式
前端
Lee川2 小时前
🎬 从标签到屏幕:揭秘现代网页构建与适配之道
前端·面试
Ticnix2 小时前
ECharts初始化、销毁、resize 适配组件封装(含完整封装代码)
前端·echarts