Q17
★ ★ ★ ★ ★
不知道高度的 div 怎么垂直居中?
⚡ 速记答案(30 秒)
Flex:display: flex; align-items: center;(配合 justify-content: center 可水平+垂直)。Grid:display: grid; place-items: center;。定位+transform:position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%);。
📖 详细讲解
标准面试回答(推荐记住)
不知道高度的元素垂直居中有几种常用方法。第一种是 Flex,父元素 display: flex 加 align-items: center,配合 justify-content: center 可以同时实现水平垂直居中。第二种是 Grid,父元素 display: grid 加 place-items: center 一行搞定。第三种是绝对定位加 transform,子元素 position: absolute,top 和 left 设为 50%,然后用 transform: translate(-50%, -50%) 把自身尺寸的一半往回移。
✅ 面试要点
- •Flex 最简洁常用
- •Grid place-items 一行搞定
- •transform 兼容性好
💻 代码示例
垂直居中三种方案
🎨 效果预览