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

相关推荐
火山引擎和TA的超级拍档们1 小时前
产品情报局 11 | AI 数据湖 LAS:打造大模型时代多模态数据底座
前端·后端
JavaGuide2 小时前
Gemini 真的变强了,写代码做视频的能力接近 Claude Opus5.5 了!
前端·ai编程
niceyayale2 小时前
WebRTC 延迟怎么调试:从 ICE 到 jitter buffer 的六个观测点
前端
aleimu2 小时前
Windows 11 右键打开 Cmder 2.0:从找不到菜单到默认使用 Cmder
前端·人工智能·后端
tryCbest2 小时前
Vue系列——第 20 篇:Vue Router 4——路由管理完全指南(上)
前端·javascript·vue.js
feixing_fx2 小时前
原始类型与引用类型:赋值时到底复制了什么
开发语言·前端·javascript·前端框架
一条破秋裤2 小时前
【1115】【多线程】【笔记】
前端·chrome·笔记
黑十2 小时前
FDE 怎么快速搭一个可演示页面?最小前端方案
java·大数据·前端·数据库·人工智能
Funlang2 小时前
在 Windows 95 上写前端
前端·javascript·windows
cidy_983 小时前
python第7课. 输入与输出
前端