CSS 实现元素水平垂直居中是布局中的常见需求,不同场景下有多种实现方式,以下是最常用的 7 种方法,适用于不同的布局环境:
一、Flex 布局(推荐,简单高效)
适用场景:任意子元素(块级 / 行内),父元素固定或自适应宽高。
核心原理:通过 display: flex 开启弹性布局,利用 justify-content(水平)和 align-items(垂直)居中。
<div class="parent">
<div class="child">我是要居中的内容</div>
</div>
.parent {
width: 300px;
height: 200px;
background: #f0f0f0;
/* 核心代码 */
display: flex;
justify-content: center; /* 水平居中 */
align-items: center; /* 垂直居中 */
}
.child {
width: 100px;
height: 50px;
background: #ff6b6b;
}
二、Grid 布局(现代布局方案)
适用场景:简单居中需求,兼容性要求不高(IE 不支持)。
核心原理:通过 display: grid 开启网格布局,直接用 place-items 简写属性居中。
.parent {
width: 300px;
height: 200px;
background: #f0f0f0;
/* 核心代码 */
display: grid;
place-items: center; /* 同时设置水平和垂直居中(等价于 align-items + justify-items) */
}
三、绝对定位 + transform(子元素宽高未知)
适用场景:子元素宽高不固定,父元素需设置 position: relative。
核心原理:绝对定位将子元素左上角定位到父元素中心,再通过 transform 向左上方偏移自身一半尺寸。
.parent {
width: 300px;
height: 200px;
background: #f0f0f0;
position: relative; /* 父元素相对定位 */
}
.child {
background: #ff6b6b;
/* 核心代码 */
position: absolute;
top: 50%; /* 垂直方向定位到50% */
left: 50%; /* 水平方向定位到50% */
transform: translate(-50%, -50%); /* 向左上方偏移自身50% */
}
四、绝对定位 + 负边距(子元素宽高已知)
适用场景:子元素宽高固定,计算精确。
核心原理:绝对定位到父元素中心后,通过负边距抵消自身一半宽高。
.parent {
width: 300px;
height: 200px;
background: #f0f0f0;
position: relative;
}
.child {
width: 100px; /* 已知宽度 */
height: 50px; /* 已知高度 */
background: #ff6b6b;
/* 核心代码 */
position: absolute;
top: 50%;
left: 50%;
margin-top: -25px; /* 高度的一半(负数值) */
margin-left: -50px; /* 宽度的一半(负数值) */
}
五、绝对定位 + margin: auto(子元素宽高已知)
适用场景:子元素宽高固定,希望自动填充剩余空间。
核心原理:绝对定位拉伸子元素至父元素四边,再通过 margin: auto 居中。
.parent {
width: 300px;
height: 200px;
background: #f0f0f0;
position: relative;
}
.child {
width: 100px;
height: 50px;
background: #ff6b6b;
/* 核心代码 */
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
margin: auto; /* 上下左右自动居中 */
}
六、table-cell 布局(兼容旧浏览器)
适用场景:需要兼容 IE8 等旧浏览器,父元素需表现为表格单元格。
核心原理:利用表格单元格的垂直居中特性,配合文本水平居中。
.parent {
width: 300px;
height: 200px;
background: #f0f0f0;
/* 核心代码 */
display: table-cell;
vertical-align: middle; /* 垂直居中 */
text-align: center; /* 水平居中(子元素为行内元素时生效) */
}
.child {
width: 100px;
height: 50px;
background: #ff6b6b;
display: inline-block; /* 让块级子元素受 text-align 影响 */
}
七、文本居中 + line-height(单行文本)
适用场景:仅用于单行文本(如按钮文字、标题)。
核心原理:通过 line-height 等于父元素高度实现垂直居中,text-align 实现水平居中。
<div class="parent">
我是单行文本
</div>
.parent {
width: 300px;
height: 100px; /* 固定高度 */
background: #f0f0f0;
/* 核心代码 */
text-align: center; /* 水平居中 */
line-height: 100px; /* 等于父元素高度,垂直居中 */
}
总结:不同场景的最佳选择
| 场景 | 推荐方法 | 优势 |
|---|---|---|
| 子元素宽高未知 | Flex 布局 / Grid 布局 | 简单直观,无需计算 |
| 子元素宽高已知 | 绝对定位 + margin: auto | 兼容性好,代码简洁 |
| 兼容旧浏览器(IE8+) | table-cell 布局 | 兼容性强 |
| 单行文本 | line-height + text-align | 最轻量的实现方式 |