如何实现水平垂直居中, position 与 z-index 怎么配合?
常见问题
- 如何实现元素水平垂直居中
- CSS 的 position 常用值有哪些,有什么区别?
- 什么情况下 z-index 不生效?
概念索引
- 居中: 让盒子在两轴上对齐容器中线;
- 定宽: 已知宽高时才能用负边距或 auto margin 算偏移;
- position: 决定元素参与哪种定位方案;
- containing block: 绝对定位的偏移基准;
- 层叠上下文: z-index 比较只在同一层内部有效;
- z-index: 同一层叠上下文内的层级号, 配合定位或层叠上下文才能真正生效;
水平垂直居中有哪些方案?
| 方案 | 写法 | 前提 |
|---|---|---|
| flex | 容器 flex 加 align-items: center 与 justify-content: center | 现代首选, 不需定宽 |
| grid | 容器 display: grid 加 place-items: center | 代码最短 |
| absolute 加 transform | 子元素 top: 50% left: 50% 加 translate(-50%, -50%) | 宽高未知也可 |
| absolute 加 margin auto | 子元素 inset: 0 加 margin: auto | 需定宽高 |
| line-height | line-height 等于容器高度 | 只适合单行文本 |
| table-cell | display: table-cell 加 vertical-align: middle | 已不推荐 |
<div class="box"><span class="dot">居中</span></div>
.box {
display: flex; align-items: center; justify-content: center;
width: 240px; height: 120px; background: #eef;
}
.dot { padding: 4px 8px; background: #fdd; }
- 水平居中: 块级定宽用
margin: 0 auto, 行内内容用text-align: center; - absolute 加 margin auto: 四向
inset: 0且宽高确定才均分; - 常见坑: 绝对定位的基准是最近的定位祖先, 忘了给父元素设
relative就变成相对视口居中; - 代价: flex 与 grid 改动最少, 老项目里 absolute 加负边距更兼容;
position 常用值有什么区别?
| 值 | 是否脱流 | 偏移基准 | 典型用途 |
|---|---|---|---|
static | 否 | 偏移无效 | 默认值 |
relative | 否 | 自身原位置 | 微调, 兼做定位祖先 |
absolute | 是 | 最近定位祖先的 padding box | 浮层, 角标, 下拉菜单 |
fixed | 是 | 视口, 祖先有 transform 时改成该祖先 | 顶栏, 全屏弹窗 |
sticky | 否 | 最近滚动容器, 越过阈值后吸附 | 吸顶表头, 侧栏目录 |
sticky失效: 祖先overflow为hidden/auto, 或父元素高度不超过自身;fixed被打破: 祖先带transform时改为相对该祖先;- 定位祖先:
position不为static即可, 惯例用relative且不写偏移; - 偏移简写:
inset: 0等价于四向都为 0; - 规范: 见 position;
.badge { position: absolute; top: -6px; right: -6px; }
什么情况下 z-index 不生效?
- 元素没定位:
static元素上的z-index被忽略, 除非它是 flex 或 grid 的 item; - 父级已成层: 子元素再高的层级也出不了父级所在的那一层;
- 比较范围:
z-index只和同一层叠上下文内的兄弟比较; - 值无效:
z-index: auto表示不参与层级比较; - 顺序打平: 同层同值时就按文档顺序, 后出现的盖住前面的;
| 常见创建层叠上下文的写法 | 说明 |
|---|---|
根元素 html | 最外层上下文 |
position 加 z-index 非 auto | 最常见的定位层 |
flex 或 grid item 加 z-index 非 auto | 不需要 position |
opacity 小于 1 | 最容易被忽略 |
transform 与 filter | 动画结束后仍然留层 |
isolation: isolate | 显式开一层 |
will-change: transform | 提前开层 |
怎么排查和修复?
- 边界: DevTools 的 Layers 面板能看到每个层叠上下文的范围;
- 修复: 把弹窗挂到
body下, 或用position: fixed的顶层容器, 绕开被压住的父级; - 预判: 老老实实写
z-index: 1/2/3也压不过opacity: 0.99的兄弟;
层叠上下文内部按什么顺序绘制?
背景与边框 → 负层级 → 块级盒 → 浮动 → 行内内容 → z-index 0/auto → 正层级
- 含义: 负
z-index的子元素会落在父级背景之上、父级内容之下; - 实践: 想让子元素盖住父级背景, 用
z-index: -1可行, 但父级必须自己成一个层; - 事件: 绘制顺序不影响点击命中, 命中仍按渲染树顺序判定;
.hero { position: relative; isolation: isolate; }
.hero::before { content: ""; position: absolute; inset: 0; z-index: -1; background: #eef; }