Make it stick! Sticky headers in CSS ๐ŸฆŽ๐Ÿ”

A blank note is clipped with a peg to a line.

Sticky headers are simply to implement in CSS. There is a specific property value for it - position: sticky!

The idea is straightforward: If an element has position: sticky, treat it as a normal position: relative block, as long as itโ€™s on screen. If the user scrolls far enough that the element (letโ€™s say itโ€™s a h1) will move off the screen, but itโ€™s parent is still visible onscreen, treat it as though it were position: fixed.

CSS introduced this property value in 2012. Initially, adoption was slow by some browser vendors, but that is no longer an issue thankfully. Now, we can embrace it without big reservations! There is a caveat with tables, which I will discuss below.

So, how do you make sticky headers with just css?

Itโ€™s super-easy!

All you do is:

CSS
.stayOnTop {
position: -webkit-sticky;
position: -moz-sticky;
position: -ms-sticky;
position: -o-sticky;
position: sticky;
top: 0;
}

The position is set through the properties: top, left, right, bottom. So, to have the element stay on top, use top: 0;.

Using the browser prefixes is still necessary for some browsers such as Safari, so itโ€™s best to add them all, and avoid cross-browser compatibility mishaps!

Tables

One of the best use cases for this is for bigggg tables. That is, tables where you want to see the column headers on top as you scroll down.

There is one caveat though, Chrome and Edge have a bug with using position: sticky on thead. So, the way around this is to apply it to th instead.

You can use it to make sticky headers on the side and top for easy cross-referencing for big data sets, maybe youโ€™re showing scientific findings like below! So, it kind of mimics frozen rows in Excel!

See the Pen Cell Zoom ๐Ÿ” by rob (@robjoeol) on CodePen.

Other use cases

Here are some other use cases I have seen on my web travels.

Hero section

It is used often to make a sticky navigation bar when there is a hero section above it. The navigation bar becomes fixed when the user scrolls past the hero section.

Reading progress bar

I think the example below is cool, but it requires some JS. A reading progress bar for a blog post. Scroll to see it in action. You can get creative with sticky too!

See the Pen Blog Reading Progress bar by Rob (@robjoeol) on CodePen.

I wrote an article about how I made this if you are interested!

Browser Support

As long as you avoid using it on thead, you are good on the major browsers (see green-shaded squares in image below). IE be damned! ๐Ÿ˜œ Click on the image to see the full list.

browser support for position sticky

Tagged