CSS定位

本页目录

CSS 定位(简洁版)

属性值速查表

值偏移基准脱离文档流典型场景
static无(默认)❌常规布局
relative自身原位置❌(占位保留)微调、作为绝对定位的父容器
absolute包含块,通常由最近的定位祖先建立✅浮窗、图标角标
fixed通常是浏览器视口✅固定导航栏、返回顶部
sticky滚动容器(混合模式)❌(占位保留)表头吸顶、侧边栏

常用代码片段

/* 相对定位微调 */
.relative { position: relative; top: 5px; }
/* 绝对定位(父级需 relative)*/
.parent { position: relative; }
.child { position: absolute; top: 0; right: 0; }
/* 固定导航栏 */
.nav { position: fixed; top: 0; width: 100%; }
/* 粘性表头 */
th { position: sticky; top: 0; }
/* 居中弹窗 */
.modal {
  position: absolute;
  top: 50%; left: 50%;
  transform: translate(-50%, -50%);
}
css

关键点

  • 偏移属性:top / right / bottom / left(仅对非static生效)
  • z-index 控制同一堆叠上下文中的顺序,也适用于 Flex 和 Grid 子项。
  • sticky 要设定偏移阈值,例如 top: 0。