前置知识: CSS

定位详解

00:00
1 min Intermediate 2026/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元素生效;同一层叠上下文比较元素无法超越父上下文

知识检测

学习进度

-- 已学文档
--% 知识覆盖率

学习推荐

专注模式