CSS position: sticky;

The CSS position: sticky property creates a hybrid positioning behavior where an element toggles between relative and fixed positioning depending on the scroll position. The element is positioned relative until it reaches a specified threshold, then becomes fixed in place.

Syntax

selector {
    position: sticky;
    top: value;
}

How It Works

A sticky element behaves like position: relative until the viewport reaches the defined offset position. Once the threshold is met, it becomes position: fixed and sticks to that position while scrolling.

Example: Basic Sticky Element

The following example creates a sticky navigation that sticks to the top when scrolling −

<!DOCTYPE html>
<html>
<head>
<style>
    .sticky {
        position: sticky;
        top: 0;
        padding: 15px;
        background-color: #ff6b35;
        color: white;
        border: 2px solid #333;
        font-weight: bold;
        text-align: center;
    }
    
    .content {
        height: 800px;
        padding: 20px;
        background-color: #f0f0f0;
        margin: 10px 0;
    }
</style>
</head>
<body>
    <div class="content">
        <h3>Content Before Sticky Element</h3>
        <p>Scroll down to see the sticky behavior in action.</p>
    </div>
    
    <div class="sticky">I will stick to the top when you scroll!</div>
    
    <div class="content">
        <h3>Content After Sticky Element</h3>
        <p>Keep scrolling to see how the sticky element remains at the top.</p>
        <p>This content extends below to demonstrate the sticky effect.</p>
    </div>
</body>
</html>
Initially, the orange sticky element appears in normal document flow. When you scroll down and the element reaches the top of the viewport, it becomes fixed and sticks to the top of the screen while the rest of the content continues scrolling beneath it.

Key Properties

Property Description
top Distance from top edge when sticky
bottom Distance from bottom edge when sticky
left Distance from left edge when sticky
right Distance from right edge when sticky

Conclusion

The position: sticky property is perfect for creating navigation bars, headers, or any content that should remain visible during scrolling. It requires at least one positioning property (top, bottom, left, or right) to define the sticky threshold.

Updated on: 2026-03-15T12:24:39+05:30

428 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements