阿杰,我帮你整理一份 CSS 居中方法大全,覆盖 水平居中、垂直居中、水平+垂直居中,包含示例和适用场景。


一、文本水平居中

.text-center {
    text-align: center;
}

<div class="text-center">我是水平居中的文本</div>

适用对象:行内元素 / 文本内容


二、块元素水平居中

1. 使用 margin: 0 auto

.box {
    width: 200px;
    margin: 0 auto;
    background: lightblue;
}

<div class="box">水平居中块元素</div>

条件:元素必须有 固定宽度


2. 使用 text-align: center + inline-block

.container {
    text-align: center;
}
.box {
    display: inline-block;
}

<div class="container">
    <div class="box">水平居中</div>
</div>

适用对象:动态宽度或不固定宽度的块元素


三、垂直居中

1. line-height(单行文本)

.box {
    height: 50px;
    line-height: 50px;
    text-align: center; /* 水平居中 */
    background: lightgreen;
}

条件:文本行数为 1 行


2. 使用 position + transform

.box {
    width: 200px;
    height: 100px;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background: lightcoral;
}

适用对象:固定/动态宽高元素都适用


3. Flexbox 垂直居中

.container {
    display: flex;
    align-items: center; /* 垂直居中 */
    justify-content: center; /* 水平居中 */
    height: 200px;
    background: #f0f0f0;
}

<div class="container">
    <div>居中内容</div>
</div>

现代布局首选方式,简洁、响应式


四、Grid 布局居中

.container {
    display: grid;
    place-items: center; /* 水平 + 垂直居中 */
    height: 200px;
    background: #ddd;
}

<div class="container">
    <div>Grid 居中</div>
</div>

CSS Grid 简化 Flexbox 多步骤操作


五、总结对比

方法水平居中垂直居中适用对象特点
text-align: center文本 / inline 元素简单快速
margin: 0 auto块元素需要固定宽度
position + transform块元素固定/动态宽高都可
Flexbox任意元素响应式,现代首选
Grid任意元素简洁,适合 Grid 布局