CSS 词条目录
前端Wiki/CSS/进阶/传统布局

position 定位

position 决定元素如何定位,配合 top/right/bottom/left 四个偏移属性使用:

  • static:默认值,不参与定位,偏移属性无效。
  • relative:相对定位,仍占据文档流原位置,偏移是「视觉上挪走」,原位置留着。也常作为绝对定位子元素的参照物。
  • absolute:绝对定位,脱离文档流,相对最近的非 static 祖先定位,找不到就相对页面。
  • fixed:固定定位,相对浏览器窗口,滚动也不动,适合悬浮客服按钮、吸顶栏。
  • sticky:粘性定位,滚动范围内表现如 relative,到达阈值后「粘」住变 fixed,做表头吸顶非常好用,注意父容器不能有 overflow:hidden。

黄金搭配:父元素 relative + 子元素 absolute,就能把角标、徽章、遮罩精确钉在父元素任意位置。

本节要点relative 占位偏移、absolute 脱流找非 static 祖先、fixed 相对窗口、sticky 阈值吸附;「父 relative 子 absolute」是定位套路之王。
CSS
<style>
  .card {
    position: relative;   /* 作为参照物 */
    width: 220px; padding: 16px;
    border: 1px solid #ddd;
  }
  .badge {
    position: absolute;   /* 脱离文档流 */
    top: -10px; right: -10px;
    background: tomato; color: #fff;
    padding: 2px 8px;
  }
  .toolbar {
    position: sticky; top: 0;
    background: #fff;
    border-bottom: 1px solid #eee;
    padding: 8px;
  }
</style>
<div class="toolbar">吸顶工具栏</div>
<div class="card">
  <span class="badge">NEW</span>
  右上角的角标
</div>