教程 css tutorial

position 定位模型

CSS 的 position 属性决定元素的定位方式,配合 top、right、bottom、left 属性可精确控制元素位置。

1. 静态定位(static)

  • 默认值,元素按正常文档流排列。
  • top、left 等属性无效。
css
position: static;

2. 相对定位(relative)

  • 元素保持在文档流中,但可相对自身正常位置偏移。
  • 偏移不会影响其他元素布局。
css
position: relative;
top: 10px;
left: 20px;

3. 绝对定位(absolute)

  • 元素脱离文档流,定位相对于最近的已定位父元素(非 static)。
  • 可使用 top、left 等属性精确定位。
  • 不占据空间,可能覆盖其他内容。
css
position: absolute;
top: 0;
right: 0;

4. 固定定位(fixed)

  • 元素脱离文档流,定位相对于浏览器窗口固定位置。
  • 滚动页面时元素位置不变。
css
position: fixed;
bottom: 10px;
right: 10px;

5. 粘性定位(sticky)

  • 介于相对定位和固定定位之间。
  • 元素在滚动到设定阈值时固定位置。
css
position: sticky;
top: 0;

position 定位示例

在线代码演示
源码
<!DOCTYPE html>
<html lang="zh-CN">

<head> <meta charset="UTF-8" /> <title>position 定位示例</title> <style> .static { position: static; background-color: #c5cae9; padding: 10px; margin-bottom: 10px; }

.relative {
  position: relative;
  top: 10px;
  left: 20px;
  background-color: #ffe082;
  padding: 10px;
  margin-bottom: 10px;
}

.absolute-container {
  position: relative;
  height: 150px;
  background-color: #b2dfdb;
  margin-bottom: 10px;
}

.absolute {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: #ffab91;
  padding: 10px;
  width: 120px;
}

.fixed {
  position: fixed;
  bottom: 10px;
  right: 10px;
  background-color: #90caf9;
  padding: 10px;
  width: 150px;
  text-align: center;
  color: #fff;
}

.sticky-container {
  height: 200px;
  overflow: auto;
  border: 1px solid #999;
  margin-top: 20px;
  padding: 10px;
}

.sticky {
  position: sticky;
  top: 0;
  background-color: #aed581;
  padding: 5px;
  font-weight: bold;
}

.content {
  height: 400px;
  background: linear-gradient(to bottom, #fff, #ddd);
  margin-top: 10px;
}

</style> </head>

<body> <div class="static">静态定位 (static)</div>

<div class="relative">相对定位 (relative),向下右偏移</div>

<div class="absolute-container"> <div>父元素相对定位容器</div> <div class="absolute">绝对定位 (absolute),右上角</div> </div>

<div class="sticky-container"> <div class="sticky">粘性定位 (sticky),顶部固定</div> <div class="content">内容区域,滚动查看效果</div> </div>

<div class="fixed">固定定位 (fixed),浏览器右下角</div> </body>

</html>