css教程网 css教程网365css.cn
公告为您打开互联网世界的窗户关于本站
首页/属性速查/布局与定位

position

让元素脱离或参与正常流,并指定其定位参照物。

语法
position: static | relative | absolute | fixed | sticky
常用值
static / relative / absolute / fixed / sticky
初始值
static
继承
否

运行效果

示例改成别的值试试,差异一眼能看出来
查看代码
HTML
<div class="p"><span class="tag">absolute</span><p>relative 容器</p></div>
CSS
.p { position: relative; width: 200px; padding: 18px; border: 1px dashed #b9c6ff; border-radius: 10px; background: #f7f9ff; font: 12px/1.5 -apple-system, sans-serif; color: #2f3846; }
.p p { margin: 0; }
.tag { position: absolute; top: -9px; right: 10px; background: #2b57ff; color: #fff; font: 600 10px/1 ui-monospace, monospace; padding: 4px 7px; border-radius: 4px; }

使用要点

  • absolute 相对最近的「已定位祖先」的 padding 盒定位,找不到则相对视口。
  • 父元素有 transform / filter / will-change 时会成为 fixed 与 absolute 的包含块,这是定位「跑偏」的常见原因。
  • sticky 需要祖先没有 overflow: hidden/auto/scroll,且自身设置了 top/bottom 阈值。