CSS 中实现 div 居中有以下几种常用方法

在 CSS 中实现 div 居中有以下几种常用方法,具体取决于需要 ​​水平居中​ ​、​​垂直居中​ ​ 还是 ​​两者兼具​​。以下是详细解决方案:

目录

[一、水平居中(Horizontal Centering)](#一、水平居中(Horizontal Centering))

[1. 行内块元素(Inline-Block)](#1. 行内块元素(Inline-Block))

[2. 固定宽度 + margin: auto](#2. 固定宽度 + margin: auto)

[3. Flexbox 弹性布局](#3. Flexbox 弹性布局)

[二、垂直居中(Vertical Centering)](#二、垂直居中(Vertical Centering))

[1. 绝对定位 + 变换(Transform)](#1. 绝对定位 + 变换(Transform))

[2. Flexbox 弹性布局](#2. Flexbox 弹性布局)

[3. Grid 网格布局](#3. Grid 网格布局)

[三、水平 + 垂直双居中(Perfect Center)](#三、水平 + 垂直双居中(Perfect Center))

[1. Flexbox(推荐)](#1. Flexbox(推荐))

[2. Grid 网格布局](#2. Grid 网格布局)

[3. 绝对定位 + 变换](#3. 绝对定位 + 变换)

四、其他场景

[1. 行内元素(Text/Inline)居中](#1. 行内元素(Text/Inline)居中)

[2. 多行文本垂直居中](#2. 多行文本垂直居中)

关键点总结



一、水平居中(Horizontal Centering)

1. 行内块元素(Inline-Block)

css

复制代码
.parent {
  text-align: center; /* 父容器设置 */
}
.child {
  display: inline-block; /* 子元素转为行内块 */
}
2. 固定宽度 + margin: auto

css

复制代码
.child {
  width: 300px;
  margin: 0 auto; /* 左右外边距自动分配 */
}
3. Flexbox 弹性布局

css

复制代码
.parent {
  display: flex;
  justify-content: center; /* 水平居中 */
}

二、垂直居中(Vertical Centering)

1. 绝对定位 + 变换(Transform)

css

复制代码
.parent {
  position: relative; /* 父容器相对定位 */
}
.child {
  position: absolute;
  top: 50%;
  transform: translateY(-50%); /* 上移自身高度的50% */
}
2. Flexbox 弹性布局

css

复制代码
.parent {
  display: flex;
  align-items: center; /* 垂直居中 */
}
3. Grid 网格布局

css

复制代码
.parent {
  display: grid;
  place-items: center; /* 垂直水平居中 */
}

三、水平 + 垂直双居中(Perfect Center)

1. Flexbox(推荐)

css

复制代码
.parent {
  display: flex;
  justify-content: center; /* 水平 */
  align-items: center;     /* 垂直 */
  height: 100vh;           /* 父容器需有高度 */
}
2. Grid 网格布局

css

复制代码
.parent {
  display: grid;
  place-items: center; /* 一步到位 */
  height: 100vh;
}
3. 绝对定位 + 变换

css

复制代码
.parent {
  position: relative;
  height: 100vh;
}
.child {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%); /* 上移左移自身尺寸的50% */
}

四、其他场景

1. 行内元素(Text/Inline)居中

css

复制代码
.parent {
  text-align: center; /* 直接继承 */
}
2. 多行文本垂直居中

css

复制代码
.parent {
  display: flex;
  align-items: center;
  line-height: 1.5; /* 与容器高度一致 */
}

关键点总结

方法 适用场景 优点 缺点
margin: auto 固定宽度元素水平居中 简单 需明确宽度
Flexbox 现代布局,支持动态尺寸 灵活,代码简洁 兼容性(IE10+)
Grid 二维布局,一步到位 强大,适合复杂设计 兼容性(IE不支持)
绝对定位 + 变换 未知尺寸元素居中 无需固定尺寸 需父容器定位

​推荐优先使用 Flexbox 或 Grid​​,它们更符合现代 Web 开发需求,且代码简洁易维护。

相关推荐
浏览器工程师1 小时前
AI Agent 接浏览器任务,先别让它一路点到底
前端·后端
雨季mo浅忆1 小时前
VSCode自动格式化三要素
前端
爱勇宝2 小时前
深扒 Anthropic 1680 位工程师简历:应届生几乎没机会,AI 公司最缺的不是博士
前端·后端·程序员
kyriewen2 小时前
同事每天催我 Code Review,我写了个脚本让 AI 替我 review PR——现在他反过来催 AI 了
前端·javascript·ai编程
user20585561518135 小时前
Windows 项目安装时报 `node-sass` 错误,如何快速处理
前端
LiaCode5 小时前
Redis 在生产项目的使用
前端·后端
LiaCode5 小时前
一天学完 redis 的爽翻版核心知识总结
前端·后端
大刚测试开发实战5 小时前
如何内网穿透访问本地私有化部署的TestHub
前端·后端·github
风骏时光牛马5 小时前
# Ruby基于Rails框架实现多角色权限管理与数据分页查询完整实战代码案例
前端
weedsfly5 小时前
迭代器、生成器与异步迭代——让数据“按需流动”的艺术
前端·javascript