Reference CSS reference

CSS position 参考

position 用于控制元素定位方式。它常见于角标、浮层、固定导航、吸顶标题和局部绝对定位。

语法

css
.badge {
  position: absolute;
  top: 8px;
  right: 8px;
}

常用值

值 说明
static 默认定位
relative 相对自身位置偏移,也可作为 absolute 子元素定位上下文
absolute 相对最近的已定位祖先定位
fixed 相对视口固定
sticky 在滚动容器中达到阈值后吸附

可运行演示

在线代码演示
源码
<!doctype html>
<html lang="zh-CN">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>position 角标演示</title>
    <style>
      body { margin: 0; padding: 24px; font-family: system-ui, sans-serif; background: #f8fafc; color: #0f172a; }
      .card { position: relative; max-width: 360px; margin: 0 auto; padding: 28px 18px 18px; border: 1px solid #dbeafe; border-radius: 12px; background: #fff; }
      .badge { position: absolute; top: 10px; right: 10px; padding: 4px 8px; border-radius: 999px; background: #2563eb; color: #fff; font-size: 12px; }
      p { margin: 8px 0 0; color: #475569; }
    </style>
  </head>
  <body>
    <article class="card">
      <span class="badge">NEW</span>
      <h1>定位上下文</h1>
      <p>父级设置 position: relative,角标使用 absolute 定位。</p>
    </article>
  </body>
</html>

常见错误

  • absolute 找不到预期父级,通常是父级忘记设置 position: relative。
  • sticky 不生效,常见原因是父级 overflow 或滚动容器不符合预期。
  • 试图用很大的 z-index 解决所有遮挡问题,但真正问题可能是 stacking context。

相关内容