position: sticky

Unique positioning that creates a sticky element.

Time to read: less than 5 min

Briefly

An element with position: sticky "sticks" to the screen when scrolling, until it meets the edge of its parent block.

Example

Let's make a "sticky" header, as well as a "sticky" block in the lower right corner for each of <section>:

        
          
          h1 {  position: sticky;  top: 15px;}.squares__item:last-of-type {  position: sticky;  bottom: 15px;}
          h1 {
  position: sticky;
  top: 15px;
}

.squares__item:last-of-type {
  position: sticky;
  bottom: 15px;
}

        
        
          
        
      
Open demo in the new window

How to understand

Blocks with "sticky" positioning behave like position: relative and position: fixed at the same time. While the block has not reached the specified distance from the edge of the browser window, it behaves as if it’s relatively positioned. When the block reaches this point, it will behave as if we specified position: fixed. And when it meets the opposite edge of the parent, it will again behave as position: relative.

How to write

        
          
          .block {  position: sticky;  top: 15px;}
          .block {
  position: sticky;
  top: 15px;
}

        
        
          
        
      

For a block that should be positioned "sticky," we specify position: sticky and the position relative to the browser window. In this example, the block will "stick" at a distance of 15 pixels from the top edge of the window.

Tips

💡 If the required element takes up the entire height of the parent block (if it is the only one in the block or simply the tallest among neighboring elements), then position: sticky will not work.

💡 When scrolling vertically, only the top and bottom properties work; when scrolling horizontally, left and right do. Or their logical equivalents inset.

💡 position: sticky can be specified within a parent with overflow: scroll or overflow: auto.

💡 If you specify a greater number of pixels for the element than the parent allows, the element will immediately align with the opposite edge of the parent block, but will not go outside the block.

In practice

Advice 1

🛠 With this positioning, it is convenient to create a sticky header - if it is a direct descendant of body, then by setting the header position: sticky, we will get a static header when the screen loads, and when scrolling the page - fixed at the top.