How to keep the header static, always on top while scrolling?

Viewed 335190

How would I go about keeping my header from scrolling with the rest of the page? I thought about utilizing frame-sets and iframes, just wondering if there is a easier and more user friendly way, what would be the best-practice for doing this?

8 Answers

position: sticky;

In modern, supported browsers, you can simply do that in CSS with -

header {
  position: sticky;
  top: 0;
  z-index: 999;
}

In most case, it is better than using position: fixed, since position: fixed takes the element out of the regular flow of elements.

Note:

  1. The HTML structure is important while using position: sticky, since it makes the element sticky relative to the parent. And the sticky positioning might not work with a single element made sticky within a parent.
  2. The parent of the element made sticky should not have the overflow property set Eg: if parent has overflow: auto or overflow: hidden, then sticky positioning might not work
  3. Giving at least one of the top, bottom, left, right is important because it makes the element sticky in relation to some position.

Run the snippet below to check a sample implementation.

main {
  padding: 0;
}
header {
  position: sticky;
  top:0;
  padding:40px;
  background: lightblue;
  text-align: center;
}

content > div {
  height: 50px;
}
<main>
  <header>
    This is my header
  </header>
  <content>
    <div>Some content 1</div>
    <div>Some content 2</div>
    <div>Some content 3</div>
    <div>Some content 4</div>
    <div>Some content 5</div>
    <div>Some content 6</div>
    <div>Some content 7</div>
    <div>Some content 8</div>
  </content>
</main>

Related