position 常用属性有哪些,默认值是什么

25 阅读3分钟

position 常用属性

position 属性用于指定元素的定位方式,它有以下几个常用值:

1. static(静态定位)  - 默认值

  • 元素按照正常的文档流进行排列
  • 忽略 topbottomleftright 和 z-index 属性
  • 不能通过 transform 以外的其他方式改变位置
.box {
  position: static; /* 默认值,通常不需要显式声明 */
}

2. relative(相对定位)

  • 元素相对于自身在文档流中的原始位置进行偏移
  • 保留原始空间,不影响其他元素布局
  • 可以使用 topbottomleftright 进行微调
.box {
  position: relative;
  top: 10px;    /* 向下移动10px */
  left: 20px;   /* 向右移动20px */
}

3. absolute(绝对定位)

  • 元素相对于最近的定位祖先元素(非 static)进行定位
  • 如果找不到定位祖先,则相对于初始包含块(通常是视口或 <html>
  • 脱离文档流,不占据空间,可能覆盖其他元素
  • 常与 relative 父元素配合使用
.parent {
  position: relative; /* 作为子元素的定位基准 */
}

.child {
  position: absolute;
  top: 0;
  right: 0;
}

4. fixed(固定定位)

  • 元素相对于浏览器视口进行定位
  • 脱离文档流,不随页面滚动而移动
  • 常用于导航栏、悬浮按钮等
.header {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
}

5. sticky(粘性定位)

  • 元素在跨越特定阈值前为相对定位,之后为固定定位
  • 需要指定 topbottomleftright 中的一个或多个作为阈值
  • 常用于表格标题、导航栏等
.sticky-header {
  position: sticky;
  top: 0; /* 当滚动到距离顶部0px时,变为固定定位 */
}

相关属性配合使用

定位元素通常需要配合以下属性:

定位坐标属性

  • top / bottom:垂直方向偏移
  • left / right:水平方向偏移
.element {
  position: absolute;
  top: 50px;
  left: 100px;
  /* 或者 bottom: 20px; right: 30px; */
}

z-index

  • 控制定位元素的堆叠顺序
  • 只对定位元素(非 static)有效
  • 数值越大,显示在越上层
.modal {
  position: fixed;
  z-index: 9999;
}

定位行为总结

定位方式定位基准是否脱离文档流是否保留原空间常用场景
static正常流默认布局
relative自身原位置微调位置,作为绝对定位的参照
absolute最近的定位祖先弹出框、图标定位
fixed浏览器视口固定导航、悬浮按钮
sticky最近的滚动祖先切换吸顶导航、表头

实际应用示例

<div class="container">
  <div class="relative-box">
    我是相对定位的父元素
    <div class="absolute-box">
      我是相对于父元素绝对定位的子元素
    </div>
  </div>
  <div class="sticky-box">滚动到顶部时会粘住</div>
</div>

<style>
.container {
  height: 2000px;
}

.relative-box {
  position: relative;
  height: 200px;
  background: #f0f0f0;
}

.absolute-box {
  position: absolute;
  bottom: 10px;
  right: 10px;
  background: #ff6b6b;
  padding: 10px;
}

.sticky-box {
  position: sticky;
  top: 0;
  background: #4ecdc4;
  padding: 20px;
}
</style>

注意事项

  1. 定位上下文absolute 和 fixed 元素会创建新的堆叠上下文
  2. 性能影响fixed 和 sticky 在移动端可能有性能问题,特别是在滚动时
  3. 浏览器兼容sticky 在 IE 和一些旧浏览器中不支持
  4. transform 的影响:父元素的 transform 属性会改变 fixed 元素的定位基准

记住:默认值总是 static,只有在需要特殊定位效果时才应该改变它。