Search code examples
htmlcsssticky

How to position sticky header on fixed position div with overflow-y: scroll


I have a pop up with information that is to be scrolled on a fixed dimensions div. The pop up also needs position: fixed, since it may appear anywhere on the site: enter image description here

HTML:

<div class="info-box">
  <div class="info-box-header">
  <a data-val="perfil" class="box-control">
    <img class="close-btn" ... />
  </a>

<h3>PERFIL</h3><br><br>
</div>

<div class="info-box-content">
    <p>Lorem ipsum...</p>
</div>

</div>

CSS:

  .info-box{
    background-color: #0f0;
    padding: 1em;
    position: fixed;
    z-index: 9999;
    width: 36em;
    height: 38em;

    overflow-y: scroll;
  }

  .info-box-content{
  }

  .info-box-header{
    position: sticky;
  }

To be able to scroll through the content and always see the close button and heading, I need the info-box-header to be a sticky header, so I tried position:sticky, however, it appears that the overflow-y:scroll of the parent .info-box doesn't care at all.

Setting the overflow-y property only for the info-box-content class has no effect. UPDATE That may be because of the height of this info-box-content class is not being set, but similar boxes with different content are required.

How would you approach this? Thanks.


Solution

  • Dimensions and overflow added for .info-box-content. Height needs to be adjusted. Is set to a small value for demo purposes.

    .info-box{
        background-color: #0f0;
        padding: 1em;
        position: fixed;
        z-index: 9999;
        width: 22em;
        height: 38em;  
    }
    
    .info-box-content{
      width: 20em;
      height: 10em;
      overflow-y: scroll;
    }
    
    .info-box-header{
        position: sticky;
    }
    <div class="info-box">
      <div class="info-box-header">
      <a data-val="perfil" class="box-control">
        <img class="close-btn" ... />
      </a>
    
    <h3>PERFIL</h3><br><br>
    </div>
    
    <div class="info-box-content">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
    </div>
    
    </div>