Role of CSS position: sticky;

The CSS position: sticky property creates elements that behave as relatively positioned until they reach a specified scroll position, then become fixed. This is particularly useful for creating navigation bars that stick to the viewport when scrolling.

Syntax

selector {
    position: sticky;
    top: value;
}

Key Properties

Property Description
position: sticky Makes the element sticky when scrolling
top Distance from top of viewport where element becomes fixed
z-index Stacking order (optional)

Example: Sticky Navigation Bar

The following example creates a navigation bar that sticks to the top of the page when scrolling −

<!DOCTYPE html>
<html>
<head>
<style>
    ul {
        list-style-type: none;
        margin: 0;
        padding: 0;
        position: sticky;
        top: 0;
        background-color: #333;
        overflow: hidden;
        z-index: 100;
    }
    li {
        float: left;
    }
    li a {
        display: block;
        color: white;
        text-align: center;
        padding: 14px 20px;
        text-decoration: none;
        transition: background-color 0.3s;
    }
    li a:hover {
        background-color: #555;
    }
    .content {
        padding: 20px;
        margin-top: 10px;
        background-color: #f1f1f1;
        height: 1500px;
    }
    h1 {
        margin-top: 0;
    }
</style>
</head>
<body>
    <ul>
        <li><a href="#home">Home</a></li>
        <li><a href="#news">News</a></li>
        <li><a href="#contact">Contact</a></li>
        <li><a href="#about">About</a></li>
    </ul>
    
    <div class="content">
        <h1>Sticky Navigation Demo</h1>
        <p>Scroll down to see the navigation bar stick to the top of the page.</p>
        <p>This content is long enough to demonstrate the sticky behavior.</p>
        <p>Keep scrolling to see how the navbar remains visible at the top.</p>
        <p>The navbar will follow you as you scroll through this content.</p>
    </div>
</body>
</html>
A dark navigation bar with white text links appears at the top. When you scroll down through the content, the navigation bar sticks to the top of the viewport and remains visible, providing easy access to navigation links.

How Sticky Positioning Works

Sticky elements have a unique behavior:

  • Initially: Acts like position: relative
  • When scrolling: Becomes position: fixed when reaching the specified threshold
  • Boundary: Stops being sticky when reaching the end of its containing element

Conclusion

The position: sticky property provides an elegant solution for creating navigation bars that remain accessible while scrolling. It combines the benefits of both relative and fixed positioning for better user experience.

Updated on: 2026-03-15T12:29:19+05:30

307 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements