Home > Software engineering >  How to make a fixed header with variable height
How to make a fixed header with variable height

Time:11-07

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.

CodePudding user response:

I think this code can help you.

window.onscroll = function() {
  var header = document.getElementsByTagName('header')
  if (document.body.scrollTop > 100 || document.documentElement.scrollTop > 100) {
      header[0].classList.add('header-scroll');
  } else {
      if (header[0].classList.contains("header-scroll")) {
          header[0].classList.remove('header-scroll');
      }
  }
}
.container {
  height: 200vh;
  padding-top: 40px;
}
header {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  background-color: green;
  box-shadow: 0 0 5px rgba(0, 0, 0, .3);
  height: 40px;
  transition: all .3s ease;
}
.header-scroll {
  height: 30px;
}
<div class="container">
<header>
</header>
<p>Scroll me</p>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

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>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related