position 控制元素如何定位,以及偏移属性 (top/right/bottom/left) 是否适用。
css
{ : static; }
{ : relative; }
{ : absolute; }
{ : fixed; }
{ : sticky; }
absolute 相对于其最近的已定位祖先元素(除 static 外的任何值)定位元素。因此,您在父元素上设置 position: relative 以使其成为参考点:
.card {
position: relative; /* becomes the positioning context */
}
.badge {
position: absolute; /* positioned relative to .card */
top: 8px;
right: 8px; /* pins the badge to the card's top-right corner */
}
这种 relative-parent / absolute-child 模式随处可见:徽章、下拉菜单、工具提示、关闭按钮。
.navbar { position: fixed; top: 0; } /* stays put on screen while scrolling */
.section-header { position: sticky; top: 0; } /* scrolls with content, then sticks at top */
top: 0),然后在其容器在视图中时保持在该位置 — 非常适合区域标题。absolute/fixed 元素被移出常规流,因此不占用空间 — 兄弟元素表现得好像它们不存在,这可能导致重叠。需要做好规划(例如添加 padding 来补偿固定导航栏)。
position 对于覆盖层、粘性标题、模态框、下拉菜单和徽章至关重要。
relative-parent/absolute-child 关系和 fixed-vs-sticky 区分是你经常使用的实际核心。