Categories
Beginner

Sticky Headers with CSS and HTML

Hey Guys!! I wanted to see if I can extend this tutorial from w3schools. What they show here is how to create a sticky header that scrolls down with the top of the page. My goal here is to check if we require any javascript for this at all. I’m looking for this particular appearance. Notice that the first statement “I come before the rest” is visible at all times when it’s in the viewport.

So first, the HTML:

<h3>I come before the rest</h3>
<div class="header sticky" id="myHeader">
      <h2>My Header</h2>
</div>
<div class="content">
      <h3>On Scroll Sticky Header</h3>
      <p>
        The header will stick to the top when you reach 
        its scroll position.
      </p>
      <p>Scroll back up to remove the sticky effect.</p>
      <p>
        Some text to enable scrolling: “Lorem ipsum dolor 
        sit amet, illum definitiones no quo, maluisset 
        concludaturque et eum, altera fabulas ut quo. 
        Atqui causae gloriatur ius te, id agam omnis 
        evertitur eum. Affert laboramus repudiandae nec 
        et. Inciderint efficiantur his ad. Eum no
        molestiae voluptatibus”.
     </p>
 <!-- Many more of these paragraphs -->
 
   </div>

Secondly, the CSS:

.header {
  padding: 10px 16px;
  background: #555;
  color: #f1f1f1;
}
 
.content {
  padding-top: 102px;
}
 
.sticky {
  position: fixed;
  top: 0;
  width: 100%;
}

But there seems to be a problem, the statement on the top is hidden behind the header. That is because we used ‘fixed’ for the header position. Luckily, there is a very simple solution. Instead of using ‘fixed’ for the position, I will use ‘sticky’:

.sticky {
  position: sticky;
  top: 0;
  width: 100%;
}

Sticky will basically tell the browser to fix the header position only when it needs to (At the point of exiting the viewport). This way, the h3 header is now in its correct place and we’re done.

Thoughts? Comments? Let me know below!

Leave a Reply

Your email address will not be published. Required fields are marked *