1. Flexbox 布局(推荐)
最简洁的现代方法,适合父容器与子元素的关系明确时:
.parent { display: flex; align-items: center; /* 垂直居中 */ justify-content: center; /* 水平居中 */ height: 500px; /* 父容器需设置高度 */ }
适用场景:无需计算尺寸,支持多行内容,兼容现代浏览器
2. 绝对定位 + Transform
适合未知子元素尺寸的动态居中:
.parent { position: relative; height: 500px; } .child { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); /* 自动计算偏移量 */ }
优势:无需固定子元素宽高,自适应内容 。
3. Grid 布局
利用 CSS Grid 的居中属性,代码更简洁:
.parent { display: grid; place-items: center; /* 同时水平和垂直居中 */ height: 500px; }
特点:二维布局控制,适合复杂结构 。
4. 绝对定位 + Margin Auto
需已知子元素尺寸,适合固定宽高场景:
.parent { position: relative; height: 500px; } .child { position: absolute; top: 0; left: 0; right: 0; bottom: 0; margin: auto; width: 200px; /* 固定宽度 */ height: 100px; /* 固定高度 */ }
注意:必须指定子元素宽高,否则会铺满父容器 。
5. Table-Cell 布局
传统方法,兼容旧版浏览器:
.parent { display: table; width: 100%; height: 500px; } .child { display: table-cell; vertical-align: middle; /* 垂直居中 */ text-align: center; /* 水平居中 */ }
适用场景:需要支持 IE8+ 等老旧浏览器 。
兼容性对比
方法 | 支持浏览器 | 需固定尺寸 | 多行内容 |
---|---|---|---|
Flexbox | IE10+(需前缀) | 否 | 支持 |
Grid | IE11+(部分) | 否 | 支持 |
绝对定位+Transform | IE9+ | 否 | 支持 |
Table-Cell | IE8+ | 否 | 支持 |
推荐选择:优先使用 Flexbox 或 Grid,复杂场景用绝对定位,老旧项目用 Table-Cell。
相关文章