CSS-面试-居中方案汇总
2026年10月16日·Admin·2 次浏览
面试题:水平垂直居中有哪些写法?
已知宽高 — 绝对定位 + 负 margin(传统)
父 position: relative,子 absolute; left/top: 50%; margin-left/top: -半宽高。
未知宽高 — 绝对定位 + transform
.child {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
注意:transform 新建层叠上下文,可能与 fixed 子元素行为一起考。
Flex(推荐)
.parent {
display: flex;
justify-content: center;
align-items: center;
}
Grid
.parent {
display: grid;
place-items: center;
}
行内/行内块
单行文本:line-height = 父高 + text-align: center(仅水平易,垂直局限多)。
面试答清:Flex/Grid 最省心;定位+transform 兼容老场景。