Creating a sticky sidebar
Create a sticky sidebar using position sticky.
In this lesson:
- Using position sticky
- Troubleshooting position sticky
Setting position sticky
Position sticky alternates the position of an element between relative and fixed based on the viewer’s scroll position. A sticky element is relative to the document flow until a defined scroll position is reached, then it switches to behaving like a fixed element within its direct parent. Once, the sticky element hits the bottom of its parent, it doesn’t scroll past it.
- With the sidebar selected, apply position sticky in the Style panel. You'll notice that if you scroll, the sidebar doesn't stick! It remains in its natural place in the document flow. That's because we didn't define a distance yet.
You must specify at least one position value for the top, bottom, left, or right side for sticky positioning to work. This depends on where your element is positioned within the parent and how you're scrolling, vertically or horizontally.
- Define a distance from the top. Set the top value to 0px if you want the sidebar to stick to the top of the page, or set another value, say 30px, to make it stick to the top of the page with a distance of 30px from the top. Now, when you scroll, the sidebar should stick to the page as long as you're scrolling within the container, the direct parent, of the sidebar.
Troubleshooting position sticky
Sometimes, position sticky won't work even though you've set the position to sticky and defined a distance value for one of the sides of the element. That can happen for many reasons:
- Position sticky will most probably not work if overflow is set to hidden, scroll, or auto on any of the parents of the element.
- Position sticky may not work correctly if any parent element has a set height.
- Many browsers still do not support sticky positioning. Check out which browsers support position: sticky.
Position sticky may also not work if the position distance value is set on a side that isn't affected by the scrolling. For example, if you set the distance on the left or right, and you're scrolling through the page vertically, the element won't stick. Another example would be if you've set a distance to the bottom, for instance, instead of the top and your element is aligned to the top of the parent — it's either the first element in the parent or aligned to the top with flex or grid alignment settings.