Fixed Position
Learn how position: fixed anchors elements to the viewport — perfect for sticky headers, floating buttons, and modals.
Fixed Position
position: fixed removes an element from the document flow and anchors it to the browser viewport. It stays in the same position even when the user scrolls.
How It Works
- The element is removed from document flow
- It is positioned relative to the viewport (browser window), not any parent
- It does not move when the page is scrolled
- Use
top,right,bottom,leftto place it
Fixed Header (Nav Bar)
.navbar {
position: fixed;
top: 0;
left: 0;
right: 0; /* Stretches full width */
height: 60px;
background: #ffffff;
box-shadow: 0 2px 8px rgba(0,0,0,0.1);
z-index: 1000;
display: flex;
align-items: center;
padding: 0 24px;
}
/* Add padding to body so content isn't hidden behind the navbar */
body {
padding-top: 60px;
}
Back-to-Top Button
.back-to-top {
position: fixed;
bottom: 24px;
right: 24px;
width: 48px;
height: 48px;
background: #6c5ce7;
color: white;
border: none;
border-radius: 50%;
cursor: pointer;
font-size: 20px;
box-shadow: 0 4px 12px rgba(0,0,0,0.2);
}
Cookie Banner / Footer Bar
.cookie-banner {
position: fixed;
bottom: 0;
left: 0;
right: 0;
padding: 16px 24px;
background: #333;
color: white;
text-align: center;
z-index: 999;
}
Fixed vs Absolute
| Feature | position: fixed | position: absolute |
|---|---|---|
| Positioned relative to | Viewport (browser window) | Nearest positioned ancestor |
| Scrolls with page? | ❌ No — stays in place | ✅ Yes — scrolls with parent |
| Removed from flow? | ✅ Yes | ✅ Yes |
| Common uses | Headers, footers, FABs | Badges, tooltips, overlays |
Important Considerations
- Body padding — add space to the body/main content so it's not hidden behind fixed elements
- Mobile viewports — fixed elements take up valuable screen space on small devices
- z-index — fixed elements often need a high
z-indexto appear above other content - transform ancestor caveat — if an ancestor has a
transform,perspective, orfilterproperty,position: fixedbehaves likeabsoluteinstead
Key Takeaways
position: fixedanchors an element to the viewport- The element stays visible even when scrolling
- Perfect for navigation bars, floating buttons, and banners
- Always add padding/margin to body to prevent content overlap
- Use
z-indexto ensure fixed elements appear on top