Search code examples
javascripthtmlcssheaderheight

How to make a fixed header with variable height


Im trying to create a fixed header with variable height. I'll explain myself, say you get into the site and the header is visible, and it is 40px of height. once you scroll down the header is now 30px, and it is fixed. How can I achieve this? I know I am supposed to write some code but I have no idea on where to start. I know how to make a fixed header but dont know how to implement the variable height feature. Any advice or code snippets are very welcome.


Solution

  • You can do it with pure CSS by nesting position: sticky; elements and give the navbar as position a top: -10px

    1. You set the <nav> to the fixed height of 40px
    2. Then you use nav { position: sticky; top: -10px; }. That will allow the navbar to scroll 10px off the viewport leaving it's height at 30px visible.
    3. To have the content such as links or text not to leave the viewport, you can wrap them inside another element and apply also display: sticky; to it. Now use top: 0; to prevent those elements from leaving the viewport.

    nav {
      position: sticky;
      top: -10px;
      height: 40px;
      background-color: red;
    }
    
    nav > div {
      position: sticky;
      top: 0;
    }
    
    
    /* for scrolling purpose only */
    body {
      min-height: 500vh;
      margin: 0;
    }
    
    /* if you want the text vertically centered */
    nav {
      display: flex;
      align-items: center;
    }
    
    nav > div {
      display: flex;
      align-items: center;
      height: 30px;
    }
    <nav>
      <div>Test</div>
    </nav>