Fixed Positioning
What you'll learn: How fixed positioning locks an element in place on the screen, even when the page scrolls.
The Core Idea
Fixed positioning removes an element entirely from the normal document flow and positions it relative to the viewport (the browser window). Unlike relatively or absolutely positioned elements, a fixed element stays in the exact same spot on your screen when you scroll—it doesn't move with the page content.
Think of it like a sticky note on your computer monitor: no matter what you do with the documents behind the screen, that sticky note stays put in the same spot on the glass.
How It Works
When you set position: fixed; on an element:
- The element is removed from normal flow (other elements behave as if it doesn't exist)
- It positions itself relative to the viewport, not any parent element
- You use the offset properties (
top,right,bottom,left) to specify exactly where it should stick - It stays in that position even when users scroll
.navbar {
position: fixed;
top: 0;
left: 0;
width: 100%;
}
This creates a navigation bar stuck to the top of the browser window.
Common Use Cases
Fixed positioning is perfect for:
- Navigation bars that stay visible while scrolling
- "Back to top" buttons in the corner
- Cookie consent banners
- Floating action buttons
Important Note
Because fixed elements are removed from normal flow, they don't take up space in the document. Other content will flow underneath them, so you might need to add padding or margin to your main content to prevent overlap.
Key Takeaway: Fixed positioning anchors an element to the viewport itself, making it scroll-proof and always visible in the same screen location.