CSS position 属性的所有取值(2024最新)

1. 基础定位值

描述 特点
static 默认值 正常文档流,top/right/bottom/left/z-index 无效
relative 相对定位 相对自身原位置偏移,占据原空间
absolute 绝对定位 相对最近的非 static 父元素,脱离文档流
fixed 固定定位 相对视口,脱离文档流
sticky 粘性定位 相对父元素,relative + fixed 混合体

2. 新增/实验性取值

sticky(已成为标准,广泛支持)

css

复制代码
.element {
  position: sticky;
  top: 0; /* 滚动到顶部时固定 */
  z-index: 100;
}
  • ✅ 已标准化,所有现代浏览器支持

  • 在滚动阈值内表现为 relative,超出表现为 fixed

-webkit-sticky(兼容前缀)

css

复制代码
.element {
  position: -webkit-sticky; /* Safari 旧版 */
  position: sticky;
}

3. 实验性/草案中的取值

position: sticky 的增强(CSS 锚点定位)

css

复制代码
.element {
  position: absolute;
  position-try-fallbacks: flip-block, flip-inline; /* 尝试不同位置 */
  position-visibility: always; /* 始终显示 */
}
position: fixed 增强

css

复制代码
/* 相对特定包含块固定 */
.element {
  position: fixed;
  position-reference: container; /* 实验性 */
}
anchor() 函数(CSS 锚点定位)

css

复制代码
/* 元素相对另一个元素定位 */
.tooltip {
  position: absolute;
  position-anchor: --anchor-el;
  top: anchor(--anchor-el bottom);
  left: anchor(--anchor-el center);
}

4. 各取值详细对比

特性 static relative absolute fixed sticky
脱离文档流 部分
占据原空间
相对谁定位 - 自身 最近定位父级 视口 父容器/视口
滚动影响 滚动 滚动 滚动 固定 粘性
z-index 生效

5. 粘性定位的常见陷阱

css

复制代码
/* 正确用法 */
.correct-sticky {
  position: sticky;
  top: 0; /* 必须设置一个阈值 */
  background: white;
  z-index: 10;
}

/* 错误用法(不会生效) */
.wrong-sticky {
  position: sticky;
  /* 缺少 top/bottom/left/right */
  background: white;
}

/* 父容器限制 */
.parent {
  overflow: hidden; /* ❌ 会破坏 sticky */
  height: 100%;
}

.parent {
  overflow: visible; /* ✅ 需要 visible */
}

总结

  • 常用static(默认)、relativeabsolutefixed

  • 推荐sticky(替代 JavaScript 的滚动监听)

相关推荐
云水一下3 小时前
TypeScript 从零基础到精通(五):高级类型与泛型
前端·javascript·typescript
counterxing3 小时前
vibe coding 之后,我更不想打字了
前端·agent·ai编程
copyer_xyf3 小时前
Python 模块与包的导入导出
前端·后端·python
研☆香3 小时前
es6新特性功能介绍(四)
前端·ecmascript·es6
微扬嘴角4 小时前
React篇1--JSX语法规则、组件、组件实例的3大特性
前端·react.js·前端框架
copyer_xyf4 小时前
Python venv 虚拟环境
前端·后端·python
无聊的老谢4 小时前
Vue 3 + TypeScript 构建大型电信运维平台的前端架构设计
前端·vue.js·typescript
xiaofeichaichai4 小时前
Map / Set / WeakMap / WeakSet
前端·javascript
李可以量化4 小时前
成交量的终极量化策略:价量共振指标完整实现(下篇)
前端·数据库·人工智能
copyer_xyf5 小时前
Python 如何同时做很多事:进程、线程、协程
前端·后端·python