亮神知识库 亮神知识库
首页
  • 手写代码

    • 手写代码系列
  • 基础知识

    • 基础
    • JS底层
    • CSS
  • 原理
  • 浏览器
  • HTTP
  • 网络安全
  • babel
  • webpack基础
  • webpack进阶
  • Vite
  • TypeScript
  • Vue2
  • Vue3
  • Node基础

    • glob
    • 模块化机制
    • 事件循环
    • KOA2框架原理
    • Node子进程
    • cluster原理(了解)
  • 教育行业2021

    • B端
    • C端
    • 工具
  • 游戏行业2025
  • 刷题
  • 杂(待整理)
  • 学习
  • 面试
  • 实用技巧
  • 心情杂货
  • 年度总结
  • 友情链接
关于
  • 分类
  • 标签
  • 归档
  • 收藏
GitHub (opens new window)

亮神

前程明亮,未来可期
首页
  • 手写代码

    • 手写代码系列
  • 基础知识

    • 基础
    • JS底层
    • CSS
  • 原理
  • 浏览器
  • HTTP
  • 网络安全
  • babel
  • webpack基础
  • webpack进阶
  • Vite
  • TypeScript
  • Vue2
  • Vue3
  • Node基础

    • glob
    • 模块化机制
    • 事件循环
    • KOA2框架原理
    • Node子进程
    • cluster原理(了解)
  • 教育行业2021

    • B端
    • C端
    • 工具
  • 游戏行业2025
  • 刷题
  • 杂(待整理)
  • 学习
  • 面试
  • 实用技巧
  • 心情杂货
  • 年度总结
  • 友情链接
关于
  • 分类
  • 标签
  • 归档
  • 收藏
GitHub (opens new window)
  • 基础

  • 手写代码

  • JS底层深入

  • CSS

    • 盒子模型
    • 水平垂直居中
      • 面试
      • flex方法
      • transform + 绝对定位
      • 负margin + 绝对定位
      • calc + 绝对定位
      • margin: auto + 绝对定位
      • table-cell
    • BFC
    • 三栏布局
    • 画三角形
    • 面试
  • 基础
  • CSS
0zcl
2021-04-30
目录

水平垂直居中

# 面试

问:写出 div 水平垂直居中 的几种方式?

# flex方法

display: flex;
justify-content: center;
align-items: center;
1
2
3

# transform + 绝对定位

position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%)
1
2
3
4

# 负margin + 绝对定位

.outer {
   position: relative;
}
.inner {
  position: absolute;
  left: 50%;
  top: 50%;
  margin-left: -50px;
  margin-top: -50px;
}
1
2
3
4
5
6
7
8
9
10

注意:此方法 需要知道 居中元素的 宽高

# calc + 绝对定位

  position: absolute;
  left: calc(50% - 50px);
  top: calc(50% - 50px);
1
2
3

注意:此方法 需要知道 居中元素的 宽高

# margin: auto + 绝对定位

position: absolute;
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
1
2
3
4
5
6

原理: 如果 left、right 和 width 都设置了具体值,并且没有占满横向空间,那么剩余空间就处于待分配状态,此时设置 margin: auto; 意味着把剩余的空间分配给 margin,并且左右均分,所以就实现了水平居中,垂直方向同理

  • left: 0; right: 0; 相当于 width: 100%;
  • top: 0; bottom: 0; 相当于 height: 100%;

# table-cell

<code>table-cell + vertical-align</code> 实现 垂直居中. 缺点:需要在外层div,设置width.

.out-box6 {
  display: table-cell;
  vertical-align: middle;
  height: 200px;
  width: 500px;
  border: 1px solid red;
}
.inner-box6 {
  width: 100px;
  height: 100px;
  margin: 0 auto;
  border: 1px solid yellow;
}
1
2
3
4
5
6
7
8
9
10
11
12
13

参考:https://liuyib.github.io/2020/04/07/css-h-and-v-center/#%E6%B0%B4%E5%B9%B3%E5%B1%85%E4%B8%AD

编辑 (opens new window)
上次更新: 2025/07/17, 07:17:44
盒子模型
BFC

← 盒子模型 BFC→

最近更新
01
2024年
07-20
02
2023年
07-20
03
2022年
07-20
更多文章>
Theme by Vdoing | Copyright © 2025-2025 亮神 | MIT License | 桂ICP备2024034950号 | 桂公网安备45142202000030
  • 跟随系统
  • 浅色模式
  • 深色模式
  • 阅读模式