In this example, We will learn how to make an element stick to the top after some scrolling using CSS. We need to set the position
property of that element to sticky. With the position: sticky
value, the element is positioned relative to the user's scroll position. It is positioned relative until it reaches the given position in the viewport then it sticks in the given position like position: fixed
.
.container-1 {
height: 200px;
width: 200px;
background-color: aqua;
position: sticky;
top: 0;
}
.container-2 {
height: fit-content;
width: 200px;
background-color: yellow;
}
Output
Here, we can see the sticky container sticks to the top after it reaches the top of the viewport while the normal container continues to scroll even after reaching the top. The top: 0
value specifies to stick the element at 0
distance gap from the top.
In this tutorial, we learned how to make an element stick to the top after some scrolling using the position: sticky
value in CSS. You can learn the other values of position
property here.