如何創建一個與CSS滾動縮小的粘性標頭?
使用position: sticky 實現粘性頭部;2. 現代CSS 可通過animation-timeline: view() 實現滾動時自動收縮,但瀏覽器支持有限;3. 生產環境中推薦結合JavaScript 監聽scroll 事件,當向下滾動超過50px 時添加.shrunk 類以縮小頭部,向上滾動時移除該類恢復原狀;4. 可選優化包括使用transform 或will-change 提升動畫性能,但需注意佈局影響;該方案兼容性好,效果流暢,適用於現代網頁設計。
Creating a sticky header that shrinks when the user scrolls down the page is a clean and modern UX pattern. You can achieve this effect using only CSS (with a bit of help from position: sticky
and scroll-driven animations), though full support for advanced scroll-based effects may require considering browser compatibility.

Here's how to create a sticky header that shrinks on scroll using pure CSS , with a fallback-friendly approach.
✅ 1. Basic Sticky Header with Smooth Shrink on Scroll
We'll use position: sticky
for the stickiness and CSS scroll-driven animations (via scroll-timeline
and animation
) — a newer but elegant method. We'll also show a simpler alternative using JavaScript if needed.

HTML Structure
<header class="sticky-header"> <div class="header-content"> <h1>My Website</h1> <nav> <a href="#">Home</a> <a href="#">About</a> <a href="#">Contact</a> </nav> </div> </header> <!-- Page content to enable scrolling --> <main> <p>Scroll down to see the effect...</p> <!-- Add more content to enable scrolling --> <div style="height: 200vh;"></div> </main>
✅ 2. CSS: Sticky Shrink on Scroll (Modern CSS with Scroll Timeline)
This method uses CSS scroll-driven animations , which are supported in modern browsers like Chrome, Edge, and Firefox (with flags).
.sticky-header { position: sticky; top: 0; background: #fff; padding: 20px 10px; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); transition: padding 0.3s ease; /* Define scroll timeline */ animation-timeline: view(); animation-name: shrink-header; animation-range: entry 0% cover 100%; animation-fill-mode: both; z-index: 1000; } .header-content h1 { margin: 0; font-size: 24px; transition: font-size 0.3s ease; } .header-content nav a { margin-left: 20px; font-size: 18px; color: #333; text-decoration: none; transition: font-size 0.3s ease; } /* Animation to shrink header */ @keyframes shrink-header { from { padding-block: 20px; } to { padding-block: 10px; } } /* Optional: shrink text as well */ .sticky-header:is(:state(shrunk)) .header-content h1 { font-size: 20px; }
? Note :
animation-timeline: view()
creates a timeline based on the element's scroll position into the viewport. This is the key to scroll-linked animations in pure CSS.
However, browser support for animation-timeline
and @scroll-timeline
is still limited. For wider compatibility, use the JavaScript fallback below.
✅ 3. Fallback: Pure CSS Minimal JavaScript (Recommended for Production)
If you need broad browser support (Safari, older Chrome, etc.), combine CSS classes with a small JavaScript to detect scroll position.
Updated CSS
.sticky-header { position: sticky; top: 0; background: #fff; padding: 20px 10px; box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1); transition: padding 0.3s ease; z-index: 1000; } .sticky-header.shrunk { padding: 10px; } .sticky-header.shrunk h1 { font-size: 20px; } .sticky-header.shrunk nav a { font-size: 16px; }
JavaScript to Add the Class on Scroll
const header = document.querySelector('.sticky-header'); let lastScrollTop = 0; window.addEventListener('scroll', () => { const currentScrollTop = window.scrollY; // Only trigger when scrolling down if (currentScrollTop > lastScrollTop && currentScrollTop > 50) { header.classList.add('shrunk'); } else { header.classList.remove('shrunk'); } lastScrollTop = currentScrollTop; });
? This approach is reliable and widely supported. The header shrinks when scrolling down past 50px and expands back when scrolling up.
✅ 4. Optional Enhancements
- Use
will-change: transform
ortransform: scale()
for smoother animations. - Add
requestAnimationFrame
to optimize scroll performance. - Debounce or throttle scroll events if needed.
Example with transform
for smoother scaling:
.sticky-header.shrunk { transform: scale(0.95); transform-origin: top center; }
But be cautious — transform
can affect layout. Stick to padding
and font-size
changes for safer results.
Summary
- Use
position: sticky
for stickiness. - For modern browsers: try CSS scroll-driven animations (
animation-timeline: view()
). - For production: use CSS transitions JavaScript to toggle a
.shrunk
class on scroll. - Always test on mobile and different screen sizes.
Basically, it's a combo of sticky positioning, smooth transitions, and scroll detection — simple but effective.
以上是如何創建一個與CSS滾動縮小的粘性標頭?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

熱AI工具

Undress AI Tool
免費脫衣圖片

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)

backdrop-filter用於對元素背後的內容應用視覺效果,1.使用backdrop-filter:blur(10px)等語法實現毛玻璃效果;2.支持blur、brightness、contrast等多種濾鏡函數並可疊加;3.常用於玻璃態卡片設計,需確保元素與背景重疊;4.現代瀏覽器支持良好,可用@supports提供降級方案;5.避免過大模糊值和頻繁重繪以優化性能,該屬性僅在元素背後有內容時生效。

首先通過JavaScript獲取用戶系統偏好和本地存儲的主題設置,初始化頁面主題;1.HTML結構包含一個按鈕用於觸發主題切換;2.CSS使用:root定義亮色主題變量,.dark-mode類定義暗色主題變量,並通過var()應用這些變量;3.JavaScript檢測prefers-color-scheme並讀取localStorage決定初始主題;4.點擊按鈕時切換html元素上的dark-mode類,並將當前狀態保存至localStorage;5.所有顏色變化均帶有0.3秒過渡動畫,提升用戶

用戶代理樣式表是瀏覽器自動應用的默認CSS樣式,用於確保未添加自定義樣式的HTML元素仍具基本可讀性。它們影響頁面初始外觀,但不同瀏覽器存在差異,可能導致不一致顯示。開發者常通過重置或標準化樣式來解決這一問題。使用開發者工具的“計算”或“樣式”面板可查看默認樣式。常見覆蓋操作包括清除內外邊距、修改鏈接下劃線、調整標題大小及統一按鈕樣式。理解用戶代理樣式有助於提升跨瀏覽器一致性並實現精準佈局控制。

Theaspect-ratioCSSpropertydefinesthewidth-to-heightratioofanelement,ensuringconsistentproportionsinresponsivedesigns.1.Itisapplieddirectlytoelementslikeimages,videos,orcontainersusingsyntaxsuchasaspect-ratio:16/9.2.Commonusecasesincludemaintainingres

鏈接的樣式應通過偽類區分不同狀態,1.使用a:link設置未訪問鏈接樣式,2.a:visited設置已訪問鏈接,3.a:hover設置懸停效果,4.a:active設置點擊時樣式,5.a:focus確保鍵盤可訪問性,始終遵循LVHA順序以避免樣式衝突,可通過添加padding、cursor:pointer和保留或自定義焦點輪廓來提升可用性和可訪問性,還可使用border-bottom或動畫下劃線等自定義視覺效果,最終確保鏈接在所有狀態下均有良好用戶體驗和可訪問性。

vw和vh單位通過將元素尺寸與視口寬度和高度關聯,實現響應式設計;1vw等於視口寬度的1%,1vh等於視口高度的1%;常用於全屏區域、響應式字體和彈性間距;1.全屏區域使用100vh或更優的100dvh避免移動瀏覽器地址欄影響;2.響應式字體可用5vw並結合clamp(1.5rem,3vw,3rem)限制最小和最大尺寸;3.彈性間距如width:80vw、margin:5vhauto、padding:2vh3vw可使佈局自適應;需注意移動設備兼容性、可訪問性及固定寬度內容衝突,建議優先使用dvh

:emptyPseudo-classSelectSelectsselemtswithnochildrenorcontent,包括pacesorcomments,sonlyTrulyEmpterementLikeMatchit; 1.ItcanhideEmptycontainersbousing:intume {note {note display:none;} toCleanuplayouts; 2.ItallowSaddingplacePlacePlacePlaceLanderStylingLingvia :: Forefore :: Forefor :: show offor :: show

Define@keyframesbouncewith0%,100%attranslateY(0)and50%attranslateY(-20px)tocreateabasicbounce.2.Applytheanimationtoanelementusinganimation:bounce0.6sease-in-outinfiniteforsmooth,continuousmotion.3.Forrealism,use@keyframesrealistic-bouncewithscale(1.1
