Home > Blockchain >  HTML/CSS Position sticky is not working properly
HTML/CSS Position sticky is not working properly

Time:02-03

I am trying to make a div position: sticky; but it doesn't work, here's my code:

body {
  height: 1000px;
}

header {
  position: absolute;
  width: 100%;
  z-index: 100;
}

.top-navbar {
  height: 100px;
  background-color: green;
}

nav {
  position: -webkit-sticky !important;
  position: sticky;
  top: 0;
  align-self: flex-start;
  background-color: orange;
}
<header>
  <div >
    <h2>top navbar</h2>
  </div>
  <nav>
    <h1>My navbar</h1>
  </nav>
</header>

CodePudding user response:

it seems you only want to keep the nav visible on scroll. In this case do it like below. Move sticky to header and consider a negative value for top equal to the height of top-navbar

body {
  height: 1000px;
}

header {
  position: sticky;
  top: -100px;
}

.top-navbar {
  height: 100px;
  background-color: green;
}

nav {
  background-color: orange;
}


h1,h2 {
  margin:0;
}
<header>
  <div >
    <h2>top navbar</h2>
  </div>
  <nav>
    <h1>My navbar</h1>
  </nav>
</header>

CodePudding user response:

Temani has a great solution, but I wanted to point out the reason your solution isn't working. Position enter image description here

CodePudding user response:

A quick fix is to add height: 100% to your header.

<style>
       body {
          height: 1000px;
        }
  
        header {
          position: absolute;
          width: 100%;
          height: 100%;
        }
  
        .top-navbar {
          height: 100px;
          background-color: green;
        }
  
        nav {
          position: -webkit-sticky;
          position: sticky;
          top: 0;
          background-color: orange;
        }
</style>
    <header>
      <div >
        <h2>top navbar</h2>
      </div>
      <nav>
        <h1>My navbar</h1>
      </nav>
    </header>
  •  Tags:  
  • Related