CSS Questions & Answers Logo
CSS Questions & Answers Part of the Q&A Network
Q&A Logo

How can I create a sticky navigation bar that stays at the top while scrolling?

Asked on Sep 01, 2025

Answer

To create a sticky navigation bar that remains at the top of the page while scrolling, you can use the CSS "position: sticky" property. This property allows an element to stick to a defined position as the user scrolls.
<!-- BEGIN COPY / PASTE -->
    <style>
      .navbar {
        position: sticky;
        top: 0;
        background-color: #333;
        color: white;
        padding: 10px;
        z-index: 1000;
      }
    </style>

    <div class="navbar">
      <h2>My Sticky Navbar</h2>
    </div>
    <div style="height: 1500px;">
      <p>Scroll down to see the sticky effect.</p>
    </div>
    <!-- END COPY / PASTE -->
Additional Comment:
  • The "position: sticky" property combines the characteristics of "relative" and "fixed" positioning.
  • Ensure the parent container has a defined height for "position: sticky" to work effectively.
  • "top: 0" specifies that the navbar should stick to the top of the viewport.
  • Use "z-index" to ensure the navbar stays above other content when it becomes sticky.
✅ Answered with CSS best practices.

← Back to All Questions
The Q&A Network