css教程网 css教程网365css.cn
公告为您打开互联网世界的窗户关于本站
首页/布局/正文
LAYOUT · 进阶

定位与层叠上下文:absolute 到底相对谁

relative、absolute、fixed、sticky 的包含块规则,z-index 为什么有时完全不起作用。

更新于 2026-11-09 阅读约 11 分钟 标签 定位 / z-index

定位的难点不是属性值,而是「相对谁」。搞不清包含块,absolute 就会跑到意料之外的位置;搞不清层叠上下文,z-index: 9999 也可能被一个 z-index: 1 压住。

五种取值的分工#

  • static:默认,按正常流排列,top/left 无效。
  • relative:相对自身原位置偏移,原位置仍然占着,不影响其它元素。
  • absolute:脱离正常流,相对最近的已定位祖先定位。
  • fixed:相对视口定位,滚动不动。祖先有 transform / filter 时会改为相对该祖先。
  • sticky:正常流中占位,滚动到阈值后「粘住」。
CSS
.card { position: relative; }        /* 建立包含块 */
.card .badge {
  position: absolute;
  top: 10px; right: 10px;            /* 相对 .card 的 padding 盒 */
}
示例真实渲染,改一个值就能看出差别
查看代码
HTML
<div class="card">
  <span class="badge">NEW</span>
  <p>卡片内容</p>
</div>
CSS
.card {
  position: relative;
  width: 220px; padding: 18px; border-radius: 12px;
  border: 1px solid #dfe5f0; background: #fff;
  font: 14px/1.6 -apple-system, "PingFang SC", sans-serif; color: #2f3846;
}
.card p { margin: 0; }
.badge {
  position: absolute; top: -9px; right: 12px;
  background: #f4512c; color: #fff; font: 700 10px/1 ui-monospace, monospace;
  padding: 5px 8px; border-radius: 5px; letter-spacing: .06em;
}

absolute 的包含块规则#

它相对最近的、position 不为 static 的祖先的 padding 盒定位。如果一路找不到,就相对初始包含块(视口大小)。

sticky 为什么常常不生效#

sticky 需要三件事同时成立:元素在滚动容器内、写了阈值(top: 0 之类)、没有任何祖先设置 overflow: hidden / auto / scroll。第三条是最常见的失败原因——祖先一旦裁剪溢出,粘性就失效了。

CSS
/* 吸顶导航 */
.head { position: sticky; top: 0; z-index: 40; }

/* 侧栏目录 */
.toc { position: sticky; top: 96px; align-self: start; }

侧栏那条 align-self: start 不能漏。在 Grid / Flex 里子项默认 stretch,高度被拉满,就没有可粘的滚动距离了。

z-index 与层叠上下文#

z-index 只在同一个层叠上下文内比较。以下情况会创建新的层叠上下文:

  • position 非 static 且 z-index 不为 auto
  • opacity 小于 1、transform、filter、backdrop-filter、will-change
  • isolation: isolate、contain: paint、position: fixed/sticky

子元素的 z-index: 9999 只在父级上下文内部有效。父级整体在第 1 层,子元素再高也上不去。

CSS
/* 把一个区域整体提层,内部随便写 */
.modal-root { position: fixed; inset: 0; z-index: 100; isolation: isolate; }

居中:三种都要会#

CSS
/* 1. 已知尺寸 */
.center { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); }

/* 2. 未知尺寸,现代写法 */
.center { position: absolute; inset: 0; margin: auto; width: fit-content; height: fit-content; }

/* 3. 首选:不需要定位 */
.center { display: grid; place-items: center; }

能用 Flex / Grid 居中就别用定位。定位居中要处理 transform 带来的层叠上下文和文本模糊问题,成本更高。