Appearance
✨ 居中总结 👌
居中:盒子在其包含块中居中
行盒(行块盒)水平居中
传统方案(CSS2)
直接设置行盒(行块盒)父元素text-align:center
css
.parent {
text-align: center;
}
.child {
display: inline-block;
/* 或 display: inline */
}现代方案(CSS3)
方案 1:Flexbox
css
.parent {
display: flex;
justify-content: center;
}方案 2:Grid
css
.parent {
display: grid;
justify-content: center;
}
/* 或者 */
.parent {
display: grid;
place-items: center; /* 同时水平垂直居中 */
}常规流块盒水平居中
传统方案(CSS2)
定宽,设置左右 margin 为 auto
css
.child {
width: 300px; /* 必须定宽 */
margin: 0 auto;
}现代方案(CSS3)
方案 1:Flexbox(推荐)
css
.parent {
display: flex;
justify-content: center;
}
.child {
/* 无需定宽 */
}方案 2:Grid
css
.parent {
display: grid;
justify-content: center;
}
/* 或使用 place-items */
.parent {
display: grid;
place-items: center;
}方案 3:Transform(不定宽)
css
.child {
position: relative;
left: 50%;
transform: translateX(-50%);
}绝对定位元素的水平居中
传统方案(CSS2)
定宽,设置左右的坐标为 0(left:0, right:0),将左右 margin 设置为 auto
css
.child {
position: absolute;
width: 300px; /* 必须定宽 */
left: 0;
right: 0;
margin: 0 auto;
}现代方案(CSS3)
方案 1:Transform(推荐,不定宽)
css
.child {
position: absolute;
left: 50%;
transform: translateX(-50%);
/* 无需定宽 */
}💡 提示:固定定位(fixed)是绝对定位(absolute)的特殊情况,方案相同
单行文本的垂直居中
传统方案(CSS2)
设置文本所在元素的行高,为需要垂直居中的区域的高度
css
.text {
height: 100px;
line-height: 100px; /* 等于高度 */
}现代方案(CSS3)
方案 1:Flexbox(推荐)
css
.parent {
display: flex;
align-items: center;
height: 100px;
}方案 2:Grid
css
.parent {
display: grid;
align-items: center;
height: 100px;
}
/* 或同时水平垂直居中 */
.parent {
display: grid;
place-items: center;
height: 100px;
}多行文本的垂直居中
传统方案(CSS2)
CSS2 没有完美方案,可以通过设置盒子上下内边距相同,达到类似的效果,但是此时盒子的高度不固定。
css
.text {
padding: 20px 0; /* 上下内边距相同 */
}现代方案(CSS3)
方案 1:Flexbox(推荐)
css
.parent {
display: flex;
align-items: center;
min-height: 200px; /* 或固定高度 */
}
.text {
/* 多行文本自动垂直居中 */
}方案 2:Grid
css
.parent {
display: grid;
align-items: center;
min-height: 200px;
}方案 3:Transform
css
.parent {
position: relative;
height: 200px;
}
.text {
position: absolute;
top: 50%;
transform: translateY(-50%);
width: 100%;
}绝对定位的垂直居中
传统方案(CSS2)
定高,设置上下的坐标为 0(top:0, bottom:0),将上下 margin 设置为 auto
css
.child {
position: absolute;
height: 200px; /* 必须定高 */
top: 0;
bottom: 0;
margin: auto 0;
}现代方案(CSS3)
方案 1:Transform(推荐,不定高)
css
.child {
position: absolute;
top: 50%;
transform: translateY(-50%);
/* 无需定高 */
}最佳实践建议
- 现代项目首选 Flexbox:语法简单,功能强大,兼容性好
- 复杂布局考虑 Grid:二维布局能力强,代码更简洁
- 需要兼容老浏览器时使用传统方案:margin auto + 定宽高
- 绝对定位场景推荐 Transform:支持不定宽高,性能好
- 单行文本仍可使用 line-height:简单高效
