Frontend Lab
← 回到所有效果
F14S005framer-motion

Sticky Section

標題釘在頂端

難度 ★★★★標籤 sticky · CSS · 滾動2 min read

效果簡述

章節標題滾到頂端時釘住,直到下一段。不需要 framer,純 CSS position: sticky 就好。很多人用 JS 寫,純粹是不知道有這語法。

↓ 滾我 · top: 0px

我會釘住

內容段落 1:當你往下滾,上面的標題會黏住, 直到整段內容被滾完才離開。

內容段落 2:當你往下滾,上面的標題會黏住, 直到整段內容被滾完才離開。

內容段落 3:當你往下滾,上面的標題會黏住, 直到整段內容被滾完才離開。

內容段落 4:當你往下滾,上面的標題會黏住, 直到整段內容被滾完才離開。

內容段落 5:當你往下滾,上面的標題會黏住, 直到整段內容被滾完才離開。

內容段落 6:當你往下滾,上面的標題會黏住, 直到整段內容被滾完才離開。

內容段落 7:當你往下滾,上面的標題會黏住, 直到整段內容被滾完才離開。

內容段落 8:當你往下滾,上面的標題會黏住, 直到整段內容被滾完才離開。

預設|top: 0 黏住到段落結束

Claude Code Prompt

💬 Claude Code Prompt
參考:S005 sticky section
技術:純 CSS position: sticky;不要用 framer / JS scroll listener

具體行為:
- section 內的 h2 加 className="sticky top-0 z-10 bg-background/95 backdrop-blur"
- 父層 section 不能有 overflow-hidden / overflow-auto(會切掉 sticky)
- top 通常 0 或 navbar 高度

限制:
- 父層任何 overflow 都會破壞 sticky
- 內容區段必須有「足夠高度」才看得到 sticky 效果
- 別跟 transform 父層混用

完整程式碼

StickySection.tsx
export function StickySection() {
return (
  <section className="space-y-6">
    <h2 className="sticky top-0 z-10 bg-background/95 px-4 py-3 backdrop-blur">
      章節標題
    </h2>
    <div className="space-y-4 px-4">
      {/* 內容必須夠高才看得到 sticky 行為 */}
      <p>段落一……</p>
      <p>段落二……</p>
      <p>段落三……</p>
    </div>
  </section>
)
}

何時用

  • ✅ 章節標題、目錄
  • ✅ 表格表頭、側邊欄
  • ✅ 文章內的進度條 / 章節導航

何時別用

  • ❌ Modal / Dialog 內(祖先有 transform 會壞)
  • ❌ 跟 overflow-hidden 父層混用
  • ❌ 內容只有一兩段(看不到效果)

我踩過的坑

  1. 祖先有 overflow 就壞了:sticky 是「對最近的 scrolling ancestor」生效。Tailwind 隨手 overflow-hidden 一加就死。

  2. z-index 一定要設:不設 z-index 滾下去會被內容蓋住。

  3. 沒背景看起來像 bug:滾到上面時內容會穿透。記得加 bg-background/95 backdrop-blur

相關效果

搜尋

按 ⌘K 隨時開啟