定位与居中
position 小结
| 值 | 参照物 | 典型用途 |
|---|---|---|
static | 默认流 | 不设偏移 |
relative | 自身原位置 | 微调偏移、z-index、给绝对子元素锚点 |
absolute | 最近 定位祖先(非 static) | 浮层、角标 |
fixed | 视口 | 顶栏、返回顶部 |
sticky | 滚动前相对流内,越过阈值后固定 | 表头吸顶 |
注意:包含块 决定 absolute 参照谁;常用 position: relative 父级 + absolute 子级。
水平垂直居中(常用)
Flex(推荐):
css
.center-flex {
display: flex;
justify-content: center;
align-items: center;
}Grid:
css
.center-grid {
display: grid;
place-items: center;
}绝对定位 + transform(已知宽高或 fit-content):
css
.box {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}行内/单行文本: text-align: center + line-height 等于容器高(仅限单行)。
z-index 与层叠上下文
只在 同一层叠上下文 内比较 z-index;新建上下文的常见条件:position 非 static 且设 z-index、opacity < 1、filter、transform 等。复杂浮层建议 统一用一层 Portal + 合理 stacking。
