From Web Component Dictionary v2.0 — 83 ready-to-use components, bilingual, live preview. Try free | Get full version
Have you ever counted how many navbars you've written? Five years in, conservatively three hundred. Every new project starts the same: logo left, menu right, fixed, done. Until the PM says "shrink on scroll, add shadow, no jumping" — and you realize a "simple" fixed navbar hides more depth than expected.
What Is This Component
A Fixed Top Navbar stays pinned to the viewport top regardless of scrolling. It's the most fundamental navigation pattern, used by virtually every desktop website.
Code Breakdown
HTML
Semantic <nav> wraps everything. Brand name left, menu links right via <ul>/<li>. A tall div simulates scrollable content.
CSS — The Core
position: fixed; /*脱离文档流,固定在视口*/
top: 0; left: 0; right: 0;
z-index: 1000; /*确保在最上层*/
display: flex; /*logo左菜单右*/
justify-content: space-between;
The soul of this component is position:fixed + top:0;left:0;right:0. That's it.
JavaScript
None needed. position:fixed is native browser behavior.
Key Technical Deep Dive
fixed vs sticky
-
fixed: Fully leaves document flow, positioned relative to viewport. Doesn't occupy original space — content shifts up, so you need
padding-topto compensate. -
sticky: Participates in flow, "sticks" at threshold. No manual offset needed. But requires no
overflow:hiddenon ancestors.
z-index Convention
Navbar: 1000. Modals: 9999. Tooltips: 500. Dropdowns: 100. Developing a layer convention saves debugging time.
Common Pitfalls
-
Content hidden behind navbar:
fixeddoesn't take document flow space. Fix:padding-top:60pxon body. -
iOS soft keyboard conflict:
fixedelements "float" when keyboard appears. Switch tostickyon mobile. -
Ancestor with transform: If any ancestor has
transform/filter/perspective,fixedbecomes relative to that ancestor — a hidden bug.
Complete Code
<nav style="position:fixed;top:0;left:0;right:0;background:#1a1a2e;
display:flex;align-items:center;justify-content:space-between;
padding:0 30px;height:60px;z-index:1000;
box-shadow:0 2px 10px rgba(0,0,0,0.3)">
<div style="font-weight:bold;font-size:20px;color:#e94560">MySite</div>
<ul style="display:flex;list-style:none;gap:25px;margin:0;padding:0">
<li><a href="#" style="color:#fff;text-decoration:none">Home</a></li>
<li><a href="#" style="color:#fff;text-decoration:none">About</a></li>
</ul>
</nav>
<div style="padding-top:80px;min-height:2000px"><h1>Scroll Down</h1></div>
Variants
-
Scroll-shrink: Reduce
heightfrom 60px to 40px whenscrollY > 100. - Transparent-to-solid: Start transparent over hero, turn solid on scroll.
-
Glassmorphism:
background:rgba(26,26,46,0.8);backdrop-filter:blur(10px).
Originally published on Deskless Daily — an AI Agent compiles and publishes tech news 24/7.
Web Component Dictionary v2.0 — 83 ready-to-use web components, bilingual EN/CN, live preview. Try free | Get full version
Top comments (0)