前置知识: CSS

定位详解

1 minIntermediate2026/6/14

static、relative、absolute、fixed、sticky

1. position 属性

定位脱离文档流参照物
static默认
relative相对定位自身原位置
absolute绝对定位最近定位祖先
fixed固定定位视口
sticky粘性定位滚动容器

2. relative

.element {
  position: relative;
  top: 10px;
  left: 20px;
}

不脱离文档流,原位置保留。常作 absolute 的参照容器。

3. absolute

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

脱离文档流,参照最近定位祖先。

4. fixed

.header {
  position: fixed;
  top: 0;
  width: 100%;
  z-index: 100;
}

参照视口,滚动时固定。注意 transform 会改变包含块。

5. sticky

.sidebar {
  position: sticky;
  top: 20px;
}
th {
  position: sticky;
  top: 0;
  background: white;
  z-index: 1;
}

阈值前 relative,达到后 fixed。必须指定 top/bottom。

6. z-index

:root {
  --z-dropdown: 100;
  --z-modal: 300;
  --z-toast: 400;
}

z-index 仅对定位元素生效;同一层叠上下文内比较;子元素无法超越父上下文。