元素水平垂直居中

72 阅读3分钟

一、基础分类与核心方案

元素居中分为 水平居中垂直居中水平垂直居中,实现方式因元素类型(块级、行内、绝对定位)和是否已知宽高而异。

二、水平居中方案

1. 行内元素(inline/inline-block)
.parent {
  text-align: center; /* 父元素设置文本居中 */
}
2. 块级元素(已知宽度)
.child {
  width: 200px;
  margin: 0 auto; /* 左右margin自动均分 */
}
3. 块级元素(未知宽度)
.child {
  display: table; /* 转换为表格布局 */
  margin: 0 auto;
}
4. 绝对定位元素
.parent {
  position: relative;
}
.child {
  position: absolute;
  left: 50%;
  transform: translateX(-50%); /* 向左平移自身宽度的50% */
}

三、垂直居中方案

1. 单行文本(已知容器高度)
.parent {
  height: 100px;
  line-height: 100px; /* 行高等于容器高度 */
  white-space: nowrap; /* 防止文本换行 */
}
2. 多行文本/块级元素(flex布局)
.parent {
  display: flex;
  align-items: center; /* 垂直居中 */
}
3. 绝对定位元素(已知高度)
.parent {
  position: relative;
}
.child {
  position: absolute;
  top: 50%;
  height: 100px;
  margin-top: -50px; /* 负margin为高度的一半 */
}
4. 绝对定位元素(未知高度)
.child {
  position: absolute;
  top: 50%;
  transform: translateY(-50%); /* 向上平移自身高度的50% */
}

四、水平垂直居中(终极方案)

1. 绝对定位 + transform(未知宽高)
.parent {
  position: relative;
}
.child {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%); /* 同时处理水平和垂直 */
}
2. flex布局(现代首选)
.parent {
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center; /* 垂直居中 */
}
3. grid布局(更简洁)
.parent {
  display: grid;
  place-items: center; /* 同时处理水平和垂直 */
}
4. table-cell布局(兼容性好)
.parent {
  display: table-cell;
  text-align: center; /* 水平居中 */
  vertical-align: middle; /* 垂直居中 */
}

五、问题

1. 问:flex布局和grid布局居中的区别?
    • flex 是一维布局(主轴+交叉轴),适合单行单列元素;
    • grid 是二维布局,适合复杂网格结构,place-items 可同时处理水平和垂直居中。
2. 问:如何在不支持transform的浏览器中实现居中?
    • 已知宽高:使用绝对定位 + 负margin(如 top: 50%; margin-top: -height/2);
    • 未知宽高:使用 display: table-cellflex(需IE10+)。
3. 问:绝对定位居中的原理是什么?
    • top: 50%; left: 50% 将元素左上角移至父容器中心;
    • transform: translate(-50%, -50%) 将元素自身向左上平移自身宽高的50%。
4. 问:行内元素垂直居中的最佳方案?
    • 单行文本:使用 line-height = 容器高度
    • 多行文本:使用 display: flex/griddisplay: table-cell

六、方案对比与场景选择

方案优点缺点兼容性
flex布局现代语法,简单高效IE10+现代项目首选
grid布局二维布局,代码更简洁IE不支持现代项目高级应用
绝对定位+transform无需知道宽高,支持动态调整IE9+兼容性较好
table-cell布局兼容性好表格布局特性可能影响其他样式全浏览器