侧边栏位置粘滞,该位置大于屏幕大小

2022-03-17 00:00:00 css css-position sticky

我有一个高度大于屏幕尺寸的侧边栏,使用position: sticky时,只有滚动到页面末尾才能看到侧边栏的底部。 例如,我如何确保在滚动时,页面的50%已经显示了侧边栏的下部?

此处代码示例:https://jsfiddle.net/zxypmqvg/3/

.main-block {
  display: flex;
}

.sidebar {
  background-color: LightCoral;
  width: 25%;
}

.sidebar-content {
  margin: 5px;
  margin-bottom: 40px;
  background-color: LimeGreen;
  position: sticky;
  top: 0;
}

.main-content {
  width: 75%;
  height: 4000px;
  background-color: LightBlue;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Document</title>
</head>

<body>
  <div class="main-block">
    <div class="sidebar">
      <div class="sidebar-content">
        <p>sometext for example for stackoverfrom</p>
        <p>sometext for example for stackoverfrom</p>
        <p>sometext for example for stackoverfrom</p>
        <p>sometext for example for stackoverfrom</p>
        <p>sometext for example for stackoverfrom</p>
        <p>sometext for example for stackoverfrom</p>
        <p>last string</p>
      </div>
    </div>
    <div class="main-content">

    </div>
  </div>
</body>

</html>

最后一个字符串仅在达到页末时显示

css

可能一个很好的做法是将此推荐答案添加到.sidebar-content

overflow-y: auto;
max-height: 100vh;

相关文章