Search code examples
cssoverflowsticky

Sticky with overflow-auto remove gap


I have this content with overflow-auto and inside a sticky on top and bottom. I want the sticky elements to be part of the content itself and don't have an extra space.

Because this is a simple example you can use a workaround of define the background-color with red, but I don't want that, it cannot be applied to my complex case.

Problem:

enter image description here

Ideal

enter image description here

.container {
  height: 200px;
  width: 200px;
  overflow: auto;
}

.content {
  height: 400px;
  width: 400px;
  background: red;
}

.stickie-top {
  position: -webkit-sticky;
  position: sticky;
  left: 0;
  top: 0;
}

.stickie-bottom {
  position: -webkit-sticky;
  position: sticky;
  bottom: 0;
  left: 0;
}
<div class="container">
  <div class="stickie-top">Sticky top</div>
  <div class="content">Lorem ipsum ...</div>
  <div class="stickie-bottom">Sticky bottom</div>
</div>

You can see the example in this: jsfiddle


Solution

  • Make their height equal to 0. For the bottom sticky you will need extra CSS to rectify the alignment

    .container {
      height: 200px;
      width: 200px;
      overflow: auto;
    }
    
    .content {
      height: 400px;
      width: 400px;
      background: red;
    }
    
    .stickie-top {
      position: sticky;
      left: 0;
      top: 0;
      height:0;
    }
    
    .stickie-bottom {
      position: sticky;
      bottom: 0;
      left: 0;
      height:0;
      display:flex;
      align-items:flex-end;
    }
    <div class="container">
      <div class="stickie-top">Sticky top</div>
      <div class="content">Lorem ipsum ...</div>
      <div class="stickie-bottom">Sticky bottom</div>
    </div>