> For the complete documentation index, see [llms.txt](https://lizh.gitbook.io/knowledge/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://lizh.gitbook.io/knowledge/css-xi-lie/05css-tan-suo-xi-lie-yuan-su-ju-zhong.md).

# CSS探索系列 元素居中

元素居中是前端开发高频基础场景，分为**水平居中、垂直居中、水平-垂直同时居中**三大类。不同方案存在各自适用条件与边界限制，例如是否要求子元素固定尺寸、是否支持多行内容、浏览器兼容性等。

![image-20260818235909873](https://my-files-1259410276.cos.ap-chengdu.myqcloud.com/md_images/image-20260818235909873.png)

```html
<style>
    section {
        display: none;
        height: 300px;
        color: #0aa;
        border: 1px solid #0aa;
    }

    section .item {
        width: 300px;
        height: 150px;
        color: #fff;
        background: #0aa;
    }
</style>
<section>
    <div class="item">
        玉炉香，红蜡泪，偏照画堂秋思。眉翠薄，鬓云残，夜长衾枕寒。梧桐树，三更雨，不道离情正苦。一叶叶，一声声，空阶滴到明。
    </div>
</section>
```

[原型 - DEMO](https://github.com/1927344728/fed-knowledge/tree/master/demo/01-v-h-center.html?type=1)

## 水平居中（2）

### margin: 0 auto

**适用：块级 block 元素，子元素需要设置确定宽度。**

**原理**：普通流块级元素，剩余可用空间被左右 `margin: auto` 平分，实现水平居中。

**注意**：子元素不设置 `width`，则 `width:auto` 会直接填满父容器，没有剩余空间，`margin:auto` 不会产生居中效果。

![image-20260819000414313](https://my-files-1259410276.cos.ap-chengdu.myqcloud.com/md_images/image-20260819000414313.png)

```html
<section>
    <div class="item" style="margin: 0 auto;">
        玉炉香，红蜡泪，偏照画堂秋思。眉翠薄，鬓云残，夜长衾枕寒。梧桐树，三更雨，不道离情正苦。一叶叶，一声声，空阶滴到明。
    </div>
</section>
```

[margin - DEMO](https://github.com/1927344728/fed-knowledge/tree/master/demo/01-v-h-center.html?type=1)

### text-align: center

**适用：行内、inline-block 元素；作用在父容器。**

**注意**：仅对行内级内容生效；块级子元素本身不会被 `text-align:center` 居中。

![image-20260819000503971](https://my-files-1259410276.cos.ap-chengdu.myqcloud.com/md_images/image-20260819000503971.png)

```html
<section>
    <div class="item" style="margin: 0 auto; text-align: center;">
        玉炉香，红蜡泪，偏照画堂秋思。眉翠薄，鬓云残，夜长衾枕寒。梧桐树，三更雨，不道离情正苦。一叶叶，一声声，空阶滴到明。
    </div>
</section>
```

[center - DEMO](https://github.com/1927344728/fed-knowledge/tree/master/demo/01-v-h-center.html?type=1)

## 垂直居中（2）

### height + line-height

父容器 `height` 与 `line-height` 设置相同数值，利用半行距均分实现单行文字视觉垂直居中。

**备注**：一旦文本换行变成多行，该方案失效；属于视觉近似居中，不同字体度量会存在微小偏移。

![image-20260819000809734](https://my-files-1259410276.cos.ap-chengdu.myqcloud.com/md_images/image-20260819000809734.png)

```html
<section>
    <span style="height: 300px; line-height: 300px;">
        玉炉香，红蜡泪，偏照画堂秋思。
    </span>
</section>
```

[line-height - DEMO](https://github.com/1927344728/fed-knowledge/tree/master/demo/01-v-h-center.html?type=3)

### 伪元素对齐（inline-block + vertical-align）

**原理**：创建一个高度 100% 的 `inline-block` 伪元素作为参考标杆，子元素同样设置 `inline-block`，二者使用 `vertical-align:middle` 完成垂直对齐。

**适用：父容器高度固定，子元素内容高度不确定（支持多行）。**

**注意**：`inline-block` 元素之间会存在空白间隙，需要父容器设置 `font-size:0` 消除；子元素要重新恢复字号。子元素宽度 100% 时，会出现右侧细微空白。

![image-20260819002152273](https://my-files-1259410276.cos.ap-chengdu.myqcloud.com/md_images/image-20260819002152273.png)

```html
<style>
    .after-vertical {
        font-size: 0;
    }
    .after-vertical .wrapper {
        font-size: 16px;
        display: inline-block;
        vertical-align: middle;
    }
    .after-vertical::after {
        display: inline-block;
        width: 0;
        height: 100%;
        content: ' ';
        visibility: hidden;
        vertical-align: middle;
    }
</style>
<section class="after-vertical">
    <div class="wrapper">
        要走的终究是要走，想离开的最终还是会离开，没有那些敷衍的理由，留下的，只是那些没有保鲜期的诺言；一本往事录，合上的是谁的归宿，那曾经盛开的花，只不过是擦肩而过的幸福。
    </div>
</section>
```

[伪元素 - DEMO](https://github.com/1927344728/fed-knowledge/tree/master/demo/01-v-h-center.html?type=4)

## 水平垂直居中（8）

### Flex 布局（现代最常用）

父容器开启 flex，`justify-content:center` 控制水平；`align-items:center` 控制垂直。

**适用范围广：块、行内元素，单行、多行内容，子元素尺寸无需固定。**

```html
<section>
    <div style="display: flex; height: 300px; justify-content: center; align-items: center;">
        <div style="width: 80%;">
            《童年．花草记忆》一念花开，一念花落。这山长水远的人世，终究是要自己走下去。人在旅途，要不断的自我救赎。(桂花)
        </div>
    </div>
</section>
```

[flex - DEMO](https://github.com/1927344728/fed-knowledge/tree/master/demo/01-v-h-center.html?type=6)

### position + transform

**原理**：先 `top:50%;left:50%` 把元素左上角移动到容器中心，再通过 `translate(-50%, -50%)` 以元素自身为基准回退一半宽高，实现居中。

**注意**：`transform` 会创建新的层叠上下文；部分旧浏览器会出现字体轻微模糊。

![](https://my-files-1259410276.cos.ap-chengdu.myqcloud.com/md_images/image-20260819205351816.png)

```html
<section style="position: relative;">
    <img style="position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); width: 240px;" src="https://my-files-1259410276.cos.ap-chengdu.myqcloud.com/md_images/梅花泪.png" />
</section>
```

[transform - DEMO](https://github.com/1927344728/fed-knowledge/tree/master/demo/01-v-h-center.html?type=8)

### Grid 布局

Grid 容器内部子项 `margin:auto` 可以同时吃掉水平、垂直两个方向剩余空间，实现完全居中。

**适用：父开启 grid，子元素设置 `margin:auto`；不需要子元素固定宽高。**

```html
<section>
    <div style="display: grid; height: 300px;">
        <div style="width: 80%; margin: auto;">
            来者要惜，去者要放。人生是一场旅行，不是所有人都会去同一个地方。路途的邂逅，总是美丽，分手的驿站，总是凄凉。不管喜与愁，该走的还是要走，该来的终究会来。人生的旅程，大半是孤单。懂得珍惜，来的俱是美丽；舍得放手，走的不成负担。对过去，要放；对现在，要惜；对将来，要信
        </div>
    </div>
</section>
```

[grid - DEMO](https://github.com/1927344728/fed-knowledge/tree/master/demo/01-v-h-center.html?type=7)

### position + margin: auto（绝对定位）

子元素设置 `position:absolute`，四个方向 `inset` 全部赋值（top、right、bottom、left）。

**注意**：子元素尺寸小于父容器，完全居中；子元素宽大于父容器，水平方向左对齐；子元素高大于父容器，垂直方向居中。

```html
<section style="position: relative; height: 500px;">
    <img
         style="position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; width: 400px;"
         src="https://my-files-1259410276.cos.ap-chengdu.myqcloud.com/nice/20190419141711_6640njffmwvi_small.jpg"
         />
</section>
```

[margin-auto - DEMO](https://github.com/1927344728/fed-knowledge/tree/master/demo/01-v-h-center.html?type=10)

### position + calc()

通过 `calc()` 直接计算定位值：`50% − 自身尺寸一半`。

**限制**：子元素必须固定宽高。

```html
<section style="position: relative;">
    <div style="position: absolute; top: calc(50% - 75px); left: calc(50% - 150px); width: 300px; height: 150px; overflow: hidden;">
        走得顺时，不必太张狂，就算你爬到了坡顶，终究还要走下坡路；<br> 走得快时，无须太得意，你的脚力总是有限的，不如放慢脚步把短暂的路走得精彩些；
        <br> 走得累时，莫要太哀叹，要知道歇一歇，经受了劳累，才知道坚强与珍惜；
        <br> 走得苦时，切勿太悲怆，生活里是没有绝路的，苦难是人生的梯，助你走出低谷和沼泽。
    </div>
</section>
```

[calc - DEMO](https://github.com/1927344728/fed-knowledge/tree/master/demo/01-v-h-center.html?type=9)

### table-cell 布局

利用表格单元格的固有特性：`text-align:center` 水平，`vertical-align:middle` 垂直。

**适用：行内、inline-block 内容；支持单行、多行文本。**

**注意**：父元素需要依赖外部容器控制整体宽高；`display:table-cell` 元素不要同时设置 `float`，会破坏表格布局。

![image-20260819002221946](https://my-files-1259410276.cos.ap-chengdu.myqcloud.com/md_images/image-20260819002221946.png)

```html
<section>
    <div style="display: table-cell; height: 300px; text-align: center; vertical-align: middle;">
        <div style="display: inline-block; width: 80%;">
            曾以为真情会在你我的心间永驻，曾以为一辈子都要爱下去。但终究，时光也会老去，人心也会变淡，走着走着便忘了曾经，想着想着便走错了地方。有一天还是要面对分离，面对这情深缘浅的现实；有一天我们会分道杨镳，变成了最熟悉的陌生人。
        </div>
    </div>
</section>
```

[table-cell - DEMO](https://github.com/1927344728/fed-knowledge/tree/master/demo/01-v-h-center.html?type=5)

### background 图片居中

`background-position:center` 实现背景图居中，可以配合 `background-size` 控制图片缩放。

**仅用于背景图片，不能控制 DOM 元素。**

```html
<section style="background: url(https://my-files-1259410276.cos.ap-chengdu.myqcloud.com/nice/20190419141711_9501mvvwvonf_small.jpg) no-repeat center; background-size: 80%; height: 500px;"></section>
```

[background - DEMO](https://github.com/1927344728/fed-knowledge/tree/master/demo/01-v-h-center.html?type=11)

### padding 填充

适用于父容器大小不固定场景，依靠上下 `padding` 撑开空间实现视觉居中；多用于内部内容高度完全动态的场景。

## 总结

**现代项目优先推荐**：

* **Flex 布局**：适用范围最广，支持任意内容类型、单行多行、动态尺寸，是当前主流方案。
* **Grid 布局**：与 Flex 类似，通过 `margin:auto` 即可实现双向居中，简洁高效。
* **position + transform**：兼容性好，适用于固定或动态尺寸，不依赖父容器布局模式。

**按需求选择**：

* **仅水平居中**：块级元素用 `margin: 0 auto`（需固定宽度）；行内元素用 `text-align: center`。
* **仅垂直居中**：单行文本用 `line-height`；多行内容用伪元素 + `vertical-align` 或 Flex。
* **水平垂直同时居中**：优先 Flex 或 Grid；需兼容旧浏览器可用 `position + transform`。

**特殊限制**：

* **position + calc()**、**position + margin（负值）**：必须固定子元素宽高，灵活性差，不推荐作为首选。
* **table-cell 布局**：适合表格类数据展示，普通场景已被 Flex 替代。
* **background 居中**：仅适用于背景图片，无法控制 DOM 元素。

选择方案时需综合考虑：内容类型（块级、行内）、尺寸是否固定、是否多行、浏览器兼容性要求。
