relative vs sticky 滚动对比

relative vs sticky 滚动对比

1. 文档说明

本文档展示了 position: relativeposition: sticky 在滚动容器中的行为区别,并提供一个动态 HTML + CSS Demo,便于直观理解。

2. 核心概念对比

属性relativesticky
是否保留原本空间
是否脱离文档流 ❌(部分情况下类似固定)
偏移参考点 元素原本位置 最近的滚动容器
滚动时是否固定位置 ✅ 到达设定阈值后固定
触发条件 需要设置 top / left / bottom / right
父容器滚出时行为 跟随滚动 随父容器滚出
常用场景 微调位置、absolute 参照 表头固定、冻结列、吸附导航

3. Demo 代码

<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>relative vs sticky 对比</title>
<style>
  body {
    font-family: sans-serif;
    margin: 0;
  }

  .container {
    width: 300px;
    height: 300px;
    overflow-y: scroll;
    border: 2px solid #333;
    margin: 50px auto;
    background: #f9f9f9;
  }

  .spacer {
    height: 600px;
    padding: 10px;
  }

  /* relative 示例 */
  .relative-box {
    position: relative;
    top: 20px;
    background: lightcoral;
    padding: 10px;
    color: white;
  }

  /* sticky 示例 */
  .sticky-box {
    position: sticky;
    top: 20px;
    background: lightseagreen;
    padding: 10px;
    color: white;
  }

  h3 {
    margin: 10px 0;
  }
</style>
</head>
<body>

<h2 style="text-align:center;">relative vs sticky 滚动对比</h2>

<div class="container">
  <div class="spacer">
    <h3>relative 元素:</h3>
    <div class="relative-box">我是 relative 元素</div>

    <h3 style="margin-top:100px;">sticky 元素:</h3>
    <div class="sticky-box">我是 sticky 元素</div>
  </div>
</div>

</body>
</html>

4. 使用说明

  1. 新建一个 .html 文件,将上述代码复制进去。

  2. 使用浏览器打开文件。

  3. 滚动容器时观察效果:

    • relative 元素:随内容滚动,不会固定。

    • sticky 元素:当滚动到距离容器顶部 20px 时固定在顶部,直到父容器滚完才离开。


 

5. 应用场景

  • relative:元素微调、为绝对定位子元素提供参考。

  • sticky:表头固定、冻结列、滚动吸附导航栏。

posted @ 2025-08-15 09:14  曲琦  阅读(10)  评论(0)    收藏  举报