CSS position 参考
position 用于控制元素定位方式。它常见于角标、浮层、固定导航、吸顶标题和局部绝对定位。
语法
.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。
相关内容
相关内容
- CSS clamp() 参考 CSS clamp() Reference,整理最小值、首选值、最大值、响应式字号、间距、容器宽度、可运行演示和常见错误。
- CSS Container Query 参考 CSS Container Query Reference,整理 container-type、container-name、@container、组件级响应式...
- CSS flex 参考 CSS flex Reference,整理 display:flex、flex-direction、justify-content、align-items、ga...
- CSS grid 参考 CSS grid Reference,整理 display:grid、grid-template-columns、gap、grid-area、auto-fit、...
- CSS :has() 参考 CSS :has() Reference,整理父选择器、条件选择、表单状态、卡片样式、可运行演示和常见错误。