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

相关推荐
驭风少年君4 小时前
《搭建属于自己的网站之网页前端学习》基础入门
前端·学习
刘一说5 小时前
深入理解 Spring Boot 嵌入式 Web 容器:从原理到性能调优
前端·spring boot·firefox
你的人类朋友5 小时前
设计模式的原则有哪些?
前端·后端·设计模式
!执行6 小时前
Web3 前端与合约交互
前端·web3·1024程序员节
潘小安6 小时前
跟着 AI 学(二)- Quill 接入速通
前端
十里-6 小时前
在 Vue2 中为 Element-UI 的 el-dialog 添加拖拽功能
前端·vue.js·ui
shada6 小时前
从Google Chrome商店下载CRX文件
前端·chrome
左耳咚6 小时前
项目开发中从补码到精度丢失的陷阱
前端·javascript·面试
黑云压城After7 小时前
vue2实现图片自定义裁剪功能(uniapp)
java·前端·javascript
芙蓉王真的好17 小时前
NestJS API 提示信息规范:让日志与前端提示保持一致的方法
前端·状态模式