Search code examples
cssoverflowcss-position

Make child sticky while parent scrolls


Let's say I have a structure similar to this:

<div id="list" style="width: 500px; height: 300px; overflow: auto;">
  <div id="list_wrapper" style="width: 700px;">
    <div class="row" style="width: 100%; height: 50px;">
      <span style="display: inline-block; width: 200px;">Title</span>
      <span>Content</span>
    </div>
    <!-- more rows -->
  </div>
</div>

The list here can scroll horizontally since the list_wrapper is larger than the list itself. I would like to archive that the Title span of the row stays sticky to the left of the list when it is scrolled horizontally but I'm not sure how to do it. Is this behavior possible with CSS only?


Solution

  • I gave the elements a background-color to distinguish them.

    It is possible to give the Title element a position: sticky;left: 0.

    <div id="list" style="width: 500px; height: 300px; overflow: auto;background:green;">
      <div id="list_wrapper" style="width: 700px;background:red;">
        <div class="row" style="width: 100%; height: 50px;">
          <span style="display: inline-block; width: 200px;position: sticky;left: 0;background: blue;">Title</span>
          <span>Content</span>
        </div>
        <!-- more rows -->
      </div>
    </div>