001-实现元素的水平垂直居中

实现元素的水平垂直居中


方法 1:Flexbox 布局(推荐)

1
2
3
4
5
.parent {
display: flex;
justify-content: center; /* 水平居中 */
align-items: center; /* 垂直居中 */
}

原理

  • display: flex 将父容器设为弹性布局。
  • justify-content 控制主轴(默认水平)对齐,align-items 控制交叉轴(默认垂直)对齐。
    优点
  • 代码简洁,现代浏览器广泛支持。
  • 无需知道子元素尺寸。
    适用场景
  • 现代浏览器项目(IE10+)。

方法 2:绝对定位 + transform

1
2
3
4
5
6
7
8
9
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}

原理

  1. top: 50%; left: 50% 将子元素左上角定位到父容器中心。
  2. transform: translate(-50%, -50%) 通过子元素自身宽高的50%反向偏移,实现真正居中。
    优点
  • 兼容性好(IE9+)。
  • 不依赖子元素尺寸。
    缺点
  • 绝对定位可能影响其他布局。

方法 3:Grid 布局

1
2
3
4
.parent {
display: grid;
place-items: center; /* 同时设置水平和垂直居中 */
}

原理

  • place-itemsalign-itemsjustify-items 的简写,直接居中所有子项。
    优点
  • 代码极简(一行搞定)。
  • 天然支持多子元素同时居中。
    适用场景
  • 现代浏览器(IE不支持)。

方法 4:绝对定位 + margin(需已知子元素尺寸)

1
2
3
4
5
6
7
8
9
10
11
12
.parent {
position: relative;
}
.child {
position: absolute;
top: 50%;
left: 50%;
width: 200px;
height: 100px;
margin-top: -50px; /* height/2 */
margin-left: -100px; /* width/2 */
}

原理

  • 通过负 margin 抵消子元素宽高的一半。
    缺点
  • 必须知道子元素精确尺寸。

方法 5:table-cell 布局(传统方法)

1
2
3
4
5
6
7
8
.parent {
display: table-cell;
text-align: center; /* 水平居中 */
vertical-align: middle; /* 垂直居中 */
}
.child {
display: inline-block; /* 或 inline */
}

原理

  • 模拟表格单元格的对齐特性。
    缺点
  • 父元素需固定宽高,且可能影响其他布局。

方法 6:line-height(单行文本垂直居中)

1
2
3
4
5
6
7
8
9
.parent {
height: 200px;
line-height: 200px; /* 等于父元素高度 */
text-align: center;
}
.child {
display: inline-block;
line-height: normal; /* 重置子元素行高 */
}

适用场景

  • 单行文本或行内元素。

总结对比

方法 是否需要子元素尺寸 兼容性 推荐度
Flexbox ❌ 不需要 IE10+ ⭐⭐⭐⭐⭐
绝对定位 + transform ❌ 不需要 IE9+ ⭐⭐⭐⭐
Grid ❌ 不需要 现代浏览器 ⭐⭐⭐⭐
绝对定位 + margin ✔️ 需要 所有浏览器 ⭐⭐
table-cell ❌ 不需要 所有浏览器 ⭐⭐

推荐选择

  • 现代项目优先用 FlexboxGrid
  • 兼容旧项目用 绝对定位 + transform