如何使用 overflow-y 将粘性 header 定位在固定位置 div 上:滚动

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

我有一个弹出窗口,其中包含要在固定尺寸上滚动的信息 div。弹出窗口也需要位置:固定,因为它可能出现在网站的任何地方:

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;
  }

为了能够滚动浏览内容并始终看到关闭按钮和标题,我需要 info-box-header 具有粘性 header,所以我尝试了 position:sticky,但是, overflow-y: parent .info-box 的滚动似乎根本不在乎。

设置 overflow-y 属性 仅对 info-box-content class 无效。 更新 可能是因为这个info-box-contentclass的高度没有设置,但是需要类似的框不同的内容。

你会如何处理这个问题?谢谢。

.info-box-content 添加了维度和溢出。需要调整高度。出于演示目的设置为较小的值。

.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>