CSS header at top of page

Like them or not, headers that stay visible at the top of the page are a very popular UI and will likely not be going away anytime. Many sites make use of this kind of header, including Reddit, Facebook, Apple, and even DEV. What do each of these sites have in common? They are all using fixed headers.

I wanted to share that there is a better way to do this, and I am curious as to why no one is taking the approach of using a sticky header instead.

The issue with fixed headers

By using position: fixed on an element like the header, the element is removed from the stack and positioned relative to the browser window. That means it no longer takes up space and any elements positioned after it will adjust to fill up that area. In regards to a header, that means elements will be placed underneath it and you'll need to accommodate for it by using padding or relative positioning.

See Dev or Apple, which use a variable to store the header height and applies padding to the body or main tag:

Or Facebook, which uses relative positioning and a top offset to adjust for spacing:

Or Reddit, which uses a margin to solve it instead:

This is probably the worst way to build a header like because it's not responsive and extra unnecessary css. I suggest that headers like this should use sticky positioning instead.

The benefits of sticky positioning

By using position: sticky on a element like the header, it does a few great things. First of all, it doesn't remove the element from the stack, so it still keeps it's real estate in the container. That means you don't have to perform any of these hacks to get the right spacing for the main content and the header. Also, it still stays at the top of page or wherever you need it based on the scroll position. So instead of:

  • Setting header to position:fixed
  • Calculating the height with JS or manually adding it to a variable
  • Adjusting the position of the content with padding, margins, or relative positioning with that variable

All you have to do is:

header { position: sticky; top: 0; }

And that's it, no extra variables or calculations needed.

Here is a very simple example in a Codepen:

Browser Support

Of course, the only downside is that it does not work on IE 11:

But really though, who is accessing the Apple website or Dev from IE11? Maybe I'm just crazy, but think there a few sites that can start making this transition over to sticky positioning.

Video liên quan

Chủ Đề