【前端 | 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;

相关推荐
ClouGence1 分钟前
2026 年自动化测试工具选型指南:8 款主流工具对比
前端·测试
lichenyang45341 分钟前
为什么需要双线程通信、JavaScriptProxy 和 runJavaScript 分别干什么
前端
以和为贵1 小时前
前端也能搞懂 RAG:用 JS 手写一条最小检索增强链路
前端·人工智能·面试
风止何安啊1 小时前
网课倍速痛点解决:一套前端代码实现自由控速播放器
前端·javascript·node.js
牧艺1 小时前
用 Next.js + React Three Fiber 打造 3D 快递仓储可视化
前端·three.js
锋行天下2 小时前
如何用Vite实现Vue组件的按需打包和远程加载
前端·vue.js·前端框架
光影少年2 小时前
原生DOM操作在React 中的注意事项
前端·javascript·react.js
用户0926292831453 小时前
CSS 代码调试总踩坑?Gemini 3.5 精准定位修复
css
禅思院4 小时前
前端部署“三层漏斗”完全指南:从CI/CD到自动回滚的工程化实战【开题】
前端·架构·前端框架
快乐肚皮5 小时前
深入理解Loop Engineering
前端·后端