CSS Position Sticky

The position: sticky property in CSS combines elements of both position: relative and position: fixed.

An element with position: sticky is positioned based on the user's scroll position and the normal flow of the document. It acts like position: relative until the user scrolls to a specified threshold, at which point it becomes position: fixed.


Basic Syntax

        
            selector {
   position: sticky;
   top: value;
   right: value;
   bottom: value;
   left: value;
}
        
    

top, right, bottom and left determine the distance of the element from the respective edges of its containing block.


Sticking Behavior and Properties

Properties: top, right, bottom, and left Sticking Behavior Example
Try yourself
        
            .container{
    position: relative;
    margin-top: 200px;
}

.sticky-box{
    position:sticky;
    background: red;
    top: 0;
}

.box, .box-1, .sticky-box{
    height: 100px;
    width: 100px;
}
.box{
    background: green;
}
.box-1{
    background: orange;
}
        
    

Use Cases

1. Table Headers

Create a sticky table header that stays visible as users scroll through a long table.

2. Navbars

Implement sticky navigation menus that remain accessible as users scroll down a webpage.