CSS position 属性详解
概览
CSS position 属性用于指定元素的定位方式,共有5个主要值:static、relative、absolute、fixed、sticky。
各属性值对比
| 属性值 | 定位基准 | 是否脱离文档流 | 是否占据空间 | 是否受滚动影响 |
|---|---|---|---|---|
static |
正常文档流 | 否 | 是 | 是 |
relative |
自身原始位置 | 否 | 是 | 是 |
absolute |
最近的非static祖先 | 是 | 否 | 是 |
fixed |
视口(viewport) | 是 | 否 | 否 |
sticky |
最近滚动祖先 | 否 | 是 | 部分 |
详细说明与示例
1. static (默认值)
.element {
position: static;
/* top, right, bottom, left, z-index 无效 */
}
- 元素按正常文档流排列
- 忽略
top,right,bottom,left,z-index属性
2. relative (相对定位)
.element {
position: relative;
top: 20px; /* 向下移动20px */
left: 30px; /* 向右移动30px */
z-index: 1; /* 可设置层级 */
}
- 相对于自身原始位置进行偏移
- 保留原有空间,其他元素不会填补其位置
- 不影响其他元素的布局
- 常用于微调元素位置或作为绝对定位的参照容器
3. absolute (绝对定位)
.parent {
position: relative; /* 创建定位上下文 */
}
.child {
position: absolute;
top: 0;
right: 0;
width: 100px;
height: 100px;
}
- 相对于最近的非static定位祖先元素(如relative、absolute、fixed)
- 如果找不到,则相对于初始包含块(通常是
<html>) - 脱离文档流,不占据空间
- 其他元素会占据其原本位置
- 常用于对话框、下拉菜单、图标定位等
4. fixed (固定定位)
.header {
position: fixed;
top: 0;
left: 0;
width: 100%;
z-index: 1000;
}
- 相对于浏览器视口(viewport)定位
- 脱离文档流,不占据空间
- 不随页面滚动而移动
- 常用于固定导航栏、返回顶部按钮、广告横幅
5. sticky (粘性定位)
.sticky-header {
position: sticky;
top: 0; /* 当滚动到距离顶部0px时变为固定 */
background: white;
}
- 混合定位:开始时为相对定位,到达阈值后变为固定定位
- 相对于最近的滚动祖先
- 不脱离文档流,始终占据空间
- 需要指定至少一个阈值(
top,right,bottom,left) - 常用于表格表头、分类导航
实际应用示例
<!DOCTYPE html>
<html>
<head>
<style>
.container {
height: 2000px;
border: 2px solid #333;
padding: 20px;
position: relative; /* 为absolute子元素创建参照 */
}
.box {
width: 100px;
height: 100px;
margin: 10px;
color: white;
text-align: center;
line-height: 100px;
}
.static {
position: static;
background: gray;
}
.relative {
position: relative;
top: 20px;
left: 50px;
background: blue;
}
.absolute {
position: absolute;
top: 10px;
right: 10px;
background: red;
}
.fixed {
position: fixed;
bottom: 20px;
right: 20px;
background: green;
}
.sticky {
position: sticky;
top: 0;
background: purple;
z-index: 10;
}
</style>
</head>
<body>
<div class="container">
<div class="box static">static</div>
<div class="box relative">relative</div>
<div class="box absolute">absolute</div>
<div class="sticky">sticky - 滚动试试</div>
<!-- 内容区域 -->
<div style="height: 800px; background: #f0f0f0; padding: 20px;">
向下滚动查看效果...
</div>
</div>
<div class="box fixed">fixed</div>
</body>
</html>
重要概念
定位上下文 (Positioning Context)
- 对于
absolute:找最近的非static祖先 - 对于
fixed:始终相对于视口 - 对于
sticky:相对于最近的滚动容器
z-index
- 仅对定位元素(非
static)有效 - 数值越大,层级越高
- 相同数值时,后出现的元素在上层
.layer1 {
position: absolute;
z-index: 10; /* 在下层 */
}
.layer2 {
position: absolute;
z-index: 20; /* 在上层 */
}
常见使用场景
- relative:微调位置、创建定位上下文
- absolute:模态框、工具提示、下拉菜单
- fixed:导航栏、侧边栏、悬浮按钮
- sticky:表头、分类筛选栏
注意事项
- 性能考虑:
fixed和absolute会创建新的层,过度使用可能影响性能 - 移动端适配:移动端对
fixed的支持可能有差异 - 父元素高度塌陷:子元素绝对定位时,父元素需设置高度或清除浮动
- sticky兼容性:部分旧浏览器不支持
sticky
快速选择指南
- 不需要特殊定位 →
static - 轻微位置调整 →
relative - 精确位置控制(相对于某个元素) →
absolute - 相对于视口固定 →
fixed - 滚动时保持可见 →
sticky