Search code examples
htmlcssvue.jsflexboxgrid-layout

How to make a docked list with sticky items on top in HTML?


I am building a single page webapp using Vue/Vuetify. In one of my views I'm trying to create a list (v-list) of items on the right side of the page. The list can be longer than the page height so a scroll is necessary. However, the rest of the page should not scroll.

I have succeeded in building this first part. The problem is that I want to be able to dock items in a non scrollable area on top of the list so that the scrollable area gets smaller.

Is this possible without recalculating the scrollable area height in javascript?

I'm using both flex box and grid box, but not very experienced in doing modern HTML.


Solution

  • Definitely use position: sticky. Just be sure to position the sticky element with top CSS property (or bottom, left, right, in other situations) and it's very important that the sticky elements are direct children of the scrolling element!

    ol {
      height: 200px;
      overflow-y: auto;
      position: relative;
    }
    
    li {
      padding: .5em 0;
    }
    
    .stickme {
      top: 0;
      position: sticky;
      background: lightgreen;
    }
    <ol>
      <li>I'm normal</li>
      <li>I'm normal</li>
      <li>I'm normal</li>
      <li>I'm normal</li>
      <li class="stickme">I'm sticky</li>
      <li>I'm normal</li>
      <li>I'm normal</li>
      <li>I'm normal</li>
      <li>I'm normal</li>
      <li>I'm normal</li>
      <li>I'm normal</li>
      <li>I'm normal</li>
      <li>I'm normal</li>
    </ol>