Skip to content

定位与居中

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-indexopacity < 1、filtertransform 等。复杂浮层建议 统一用一层 Portal + 合理 stacking