How to Create a Sticky Header with Two line of Code

A sticky header stays at the top of the page as you scroll down, keeping your navigation or important information always visible. Here’s how to create one with just a two lines of CSS!


Simple Steps to Create a Sticky Header

Basic CSS for Sticky Header

Add this CSS to your header element


  
nav {
  position: sticky;
  top: 0;
}


This CSS rule makes the header "stick" to the top of the page as you scroll

The position: sticky; property sticks the header to the top, while top: 0; keeps it at the top of the viewport

Let's see some demo's and understand how it works

HTML Structure


  
<body>
  <nav>
    <ul>
      <li><a href="#first">First</a></li>
      <li><a href="#second">Second</a></li>
      <li><a href="#third">Third</a></li>
    </ul>
  </nav>
  <section id="first">First Section</section>
  <section id="second">Second Section</section>
  <section id="third">Third Section</section>
</body>



CSS


  
body {
  min-height: 100vh;
  font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
nav {
  position: sticky;
  top: 0;
}
ul {
  width: 100%;
  display: flex;
  justify-content: flex-end;
  box-sizing: border-box;
  padding: 20px;
  background: #fff;
}
li {
  list-style: none;
  margin-right: 20px;
  font-size: 25px;
  font-weight: bold;
}
li a {
  text-decoration: none;
  color: #1ac;
}
section {
  height: 100vh;
  display: grid;
  place-items: center;
  font-size: 50px;
  font-weight: bold;
  background: #eee;
}

An element with position: sticky; is positioned based on the user's scroll position.


Pro Tip

Make sure the parent container has enough height, or else the sticky element might not work as expected

Articles you may found Useful

 Ream Section using HTML and CSS

 Top 3 Free Web development courses

 JavaScript Roadmap

If you like, you can subscribe my youtube channel. I create awesome web contents. Subscribe

Thanks For reading.

Previous Post Next Post