Episode 10 of 23

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

  1. The element is removed from document flow
  2. It is positioned relative to the viewport (browser window), not any parent
  3. It does not move when the page is scrolled
  4. Use top, right, bottom, left to 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

Featureposition: fixedposition: absolute
Positioned relative toViewport (browser window)Nearest positioned ancestor
Scrolls with page?❌ No — stays in place✅ Yes — scrolls with parent
Removed from flow?✅ Yes✅ Yes
Common usesHeaders, footers, FABsBadges, 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-index to appear above other content
  • transform ancestor caveat — if an ancestor has a transform, perspective, or filter property, position: fixed behaves like absolute instead

Key Takeaways

  • position: fixed anchors 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-index to ensure fixed elements appear on top