DEV Community

Cover image for How I Use CSS Grid for Sticky Headers
Xaver Fleer
Xaver Fleer

Posted on • Edited on

How I Use CSS Grid for Sticky Headers

Adam Racki's great blog post made me realize that it is possible to use display: grid to create sticky headers. As much as the contribution inspired me, it also confused me (why all this complexity in the code examples??). Here is what I took from it:

  1. Sticky headers traditionally get positioned with display: absolute; or display: fixed;.

  2. While this does work, there is a much more elegant syntax with display: grid.

Demo:

Code

HTML

<!DOCTYPE html>
<html>

<head>
  <title>Sticky Header</title>
  <meta charset="UTF-8" />
</head>

<body id="wrapper">
  <h1 id="sticky">A Panda Bear</h1>
  <main id="scroll-element">
  <img alt="A panda bear" height="500px" src="https://images.unsplash.com/photo-1526716121440-dc3b4f254a0a"/>
  </main>
</body>

</html>

CSS

#wrapper { height: 500px; display: grid; }
#scroll-element { overflow: auto; }

What's the magic?

tbh, there is none (as with everything you understand).

Really, what's going on?

Together the heading and the content are larger than what can be shown at once. The image is stands for lot of content. It has a fixed (large) height.

The CSS rule overflow: auto; allows the browser to scroll the id="scroll-element".

The header with id="sticky" is always completely shown since the id="scroll-element" can shrink and overflow.

That's it.

Top comments (1)

Collapse
 
jaaayson profile image
Jason Cravens

#sticky { position: sticky; top: 0; }