← 返回完整题库
CSS简单

未知高度和宽度元素的水平垂直居中的方案有哪些, 简单手写一下?

参考答案

Flex

.parent { display: flex; justify-content: center; align-items: center; }

Grid

.parent { display: grid; place-items: center; }

absolute + transform

.parent { position: relative; }
.child { position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); }

table-cell(老兼容)

.parent { display: table-cell; text-align: center; vertical-align: middle; }
.child { display: inline-block; }

现代业务首选 flex/grid;浮层用 absolute+transform。

本题来自 计算机知识面试题库,共 921 道题。