全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-16 6 分钟 ✍️ juanwangdev

CSS定位

定位(position)用于精确控制元素在页面中的位置,是实现复杂布局的关键技术。

定位类型

说明是否脱离文档流
static默认,正常文档流
relative相对定位
absolute绝对定位
fixed固定定位
sticky粘性定位否(滚动时切换)

相对定位 relative

相对于元素原位置偏移,原空间保留:

CSS
.box {
  position: relative;
  top: 20px;
  left: 30px;
}

/* 常用于:微调位置、作为绝对定位的参照 */

绝对定位 absolute

相对于最近的定位祖先元素定位:

CSS
.parent {
  position: relative; /* 建立定位上下文 */
}

.child {
  position: absolute;
  top: 10px;
  right: 10px;
}

/* 居中定位 */
.center {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

固定定位 fixed

相对于视口定位,不随滚动:

CSS
.header {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  z-index: 1000;
}

.back-to-top {
  position: fixed;
  bottom: 30px;
  right: 30px;
}

粘性定位 sticky

滚动到阈值前为相对定位,之后为固定定位:

CSS
.section-title {
  position: sticky;
  top: 60px; /* 滚动到距顶部60px时固定 */
}

/* 导航栏吸顶效果 */
.nav {
  position: sticky;
  top: 0;
  z-index: 100;
}

定位偏移属性

CSS
.element {
  position: absolute;
  top: 10px;    /* 距顶部 */
  right: 20px;   /* 距右侧 */
  bottom: 10px;  /* 距底部 */
  left: 20px;    /* 距左侧 */
}

/* 拉伸效果 */
.stretch {
  position: absolute;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
}

z-index 层级控制

CSS
.modal {
  position: fixed;
  z-index: 1000; /* 值越大越在上层 */
}

.overlay {
  position: fixed;
  z-index: 999;
}

/* 注意:仅定位元素(非static)z-index生效 */

注意:绝对定位元素若找不到定位祖先,则相对于初始包含块(通常是视口)定位。

要点总结

  • relative 相对自身偏移,原空间保留,常作定位参照
  • absolute 相对于最近的定位祖先定位,脱离文档流
  • fixed 相对于视口定位,适合固定导航、弹窗
  • sticky 结合相对与固定定位,适合吸顶导航
  • z-index 控制层级,仅对定位元素生效

📝 发现内容有误?点击此处直接编辑

← 上一篇 CSS Grid布局
下一篇 → CSS浮动
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库