Building an Animated Sticky Header With Custom Offset

Sticky elements are used all across the web. With the appearance of the position: sticky property, we could create sticky elements without JavaScript plugins. But creating sticky elements with animations couldn’t be achieved without a little bit of JavaScript.

The specifications

The task is to build a sticky header that appears when the user scrolls past the static header or on a custom offset position. When scrolling down, the static header should stay at its place, while the sticky header should roll down. When scrolling up, the sticky header should disappear, and the static header should roll down. Note that the content of the static header and the sticky header differs.

The solution

To make it easier to understand the specifications, see this pen that contains the full solution:

The breakdown

For a better understanding of how this code works, we should examine the HTML structure.

.header--alpha, our static header is visible by default. When the user scrolls past the offset, and the wrapper header element becomes sticky, it will be translated outside of the wrapper element instantaneously without any transition effect. Note that element will be transitioned when it goes to the original position when sticky effect won’t be active.

.header--beta, our sticky header is positioned absolutely and translated outside of the wrapper header element. When the sticky effect is activated, it will be translated and transitioned in the original position.

JavaScript

You might have noticed the .fake-header element.

1234

.fake-header {height: 1px;position: relative;}

This element serves as an offset for the scroll. When it reaches the top of the viewport, the header becomes sticky. And when the header becomes sticky, the fake element will be pushed up by the height of the header plus one extra pixel. When the user scrolls up and reaches the fake element in its new position, the sticky effect will be turned off.

Conclusion

I am really excited to see how fast CSS is moving. Brand new properties, like position: sticky and pointer-events allows us to create better experience for the end user more easily and natively. And support is getting better and better every day. 🏆