Search code examples
csscss-positionsticky

CSS Sticky - How to sticky aside to fill available height?


I want to create grid layout and I want to aside to be sticky to top: 0 and fill all remaining height e.g. 100% of height and when I scroll down I need to change aside height to 100% subtract footers height. It's can be done without JS?

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

.grid {
  display: grid;
  grid-template-areas: "aside content"
    "footer footer";
  grid-template-columns: 20rem 1fr;
}

aside {
  grid-area: aside;
  background-color: red;

}
nav {
  font-size: 2rem;
  color: black;
  position: sticky;
  top: 0;
  
  height: 100%;
  background-color: yellow;
}
main {
  grid-area: content;
  background-color: green;
  height: 150vh;
}
footer {
  grid-area: footer;
  background-color: blue;
  height: 10rem;
}

ul {
  list-style: none;
}
<div class="grid">
  <aside>
  <nav>
    <ul>
      <li>1</li>
      <li>2</li>
      <li>3</li>
      <li>4</li>
    </ul>
  </nav></aside>
  <main>Content</main>
  <footer>Footer</footer>
</div>


Solution

  • Replace height:100% with min-height:100vh

    * {
      padding: 0;
      margin: 0;
      box-sizing: border-box;
    }
    
    .grid {
      display: grid;
      grid-template-areas: "aside content"
        "footer footer";
      grid-template-columns: 20rem 1fr;
    }
    
    aside {
      grid-area: aside;
      background-color: red;
    
    }
    nav {
      font-size: 2rem;
      color: black;
      position: sticky;
      top: 0;
      
      min-height:100vh;
      background-color: yellow;
    }
    main {
      grid-area: content;
      background-color: green;
      height: 150vh;
    }
    footer {
      grid-area: footer;
      background-color: blue;
      height: 10rem;
    }
    
    ul {
      list-style: none;
    }
    <div class="grid">
      <aside>
      <nav>
        <ul>
          <li>1</li>
          <li>2</li>
          <li>3</li>
          <li>4</li>
        </ul>
      </nav></aside>
      <main>Content</main>
      <footer>Footer</footer>
    </div>