【问题标题】:Stop sticky scroll when at the bottom of div在 div 底部时停止粘性滚动
【发布时间】:2021-06-27 02:00:01
【问题描述】:

我有一个粘性侧边栏,当您向下滚动主要内容时,它的工作方式与我想要的一样(它会粘在我想要的位置),但是当我到达页面底部时,由于某种原因,侧边栏会松开并不断向上滚动,使侧边栏菜单中的顶部几个项目消失在我的固定标题后面。

我认为这是由于我为粘性元素定义的 CSS 高度属性,我已将其设置为 100vh。

如何设置我的粘性侧边栏,以便当我点击页面底部时,它不会一直向上滚动?

这是我在这部分的代码,如果更简单,这里是一个URL 到网站的工作版本。

这是我的 HTML 和 CSS

  /* sidebar styling */

aside {
  height: 100vh;
  width: 160px;
  margin-left: -0.5em;
  position: sticky;
  z-index: 0.5;
  top: 4em;
  left: 0;
  background-color: lightblue;
  overflow-x: hidden;
}

aside a {
  padding: 6px 8px 6px 16px;
  text-decoration: none;
  font-size: 1.25em;
  color: black;
  display: block;
}

aside a:hover:not(.current-menu-item) {
  background-color: tan;
  font-weight: bold;
}

.current-menu-item {
  background-color: white;
  font-weight: bold;
}


/* main content styling */

.content {
  margin-left: 160px;
  font-size: 28px;
  padding: 0em 0.5em;
}

a.anchor {
  display: block;
  position: relative;
  top: -75px;
  visibility: hidden;
<section>

  <aside>
    <a class="menu-item-1" href="#target1">About</a>
    <a class="menu-item-2" href="#target2">Services</a>
    <a class="menu-item-3" href="#target3">Clients</a>
    <a class="menu-item-4" href="#target4">Contact</a>
  </aside>

  <div class="content">

    <a class="anchor" id="target1"></a>
    <h2>Title 1</h2>
    <h4>Subheading</h4>
    <p>Text</p>
    <h4>Subheading</h4>
    <p>Text</p>
    <h4>Subheading</h4>
    <p>Text</p>

    <a class="anchor" id="target2"></a>
    <h2>Title 1</h2>
    <h4>Subheading</h4>
    <p>Text</p>
    <h4>Subheading</h4>
    <p>Text</p>
    <h4>Subheading</h4>
    <p>Text</p>

    <a class="anchor" id="target3"></a>
    <h2>Title 1</h2>
    <h4>Subheading</h4>
    <p>Text</p>
    <h4>Subheading</h4>
    <p>Text</p>
    <h4>Subheading</h4>
    <p>Text</p>

    <a class="anchor" id="target4"></a>
    <h2>Title 1</h2>
    <h4>Subheading</h4>
    <p>Text</p>
    <h4>Subheading</h4>
    <p>Text</p>
    <h4>Subheading</h4>
    <p>Text</p>

  </div>

</section>

【问题讨论】:

    标签: html css sticky


    【解决方案1】:

    我认为这是由于我定义的 CSS 高度属性 我的粘性元素,我设置为 100vh。

    你是对的。一旦滚动通过粘性元素的高度,它就不会再粘在屏幕上。这是因为position sticky still sets an element in the normal flow

    解决方案

    1. div.content的高度设置为与粘性元素相同
    2. 去掉body的默认边距

    这样,您不会滚动传递窗口中粘性元素的高度。因此,问题不会发生。

    1. 现在,div.content 的最后一个元素因额外的填充而溢出。因此,设置overflow: hidden 使其高度与粘性元素保持一致。
    2. body 具有默认边距。因此,请将 margin: 0 设置为它。

    它将把大部分东西固定在正确的位置,但仍然定义了一些不必要的样式。因此,您可以根据需要修复其余部分。祝你好运,我希望我回答了你的问题。

    【讨论】:

    • 非常感谢。在 div.content 上设置 overflow:hidden 停止了一些滚动,然后我还将
    • 我很高兴你做到了..!有很多样式定义,所以我认为其中一些可能会影响粘性滚动。而不是看那些,我只想回答位置粘性如何工作以及解决您问题的核心解决方案。当您编写更多代码时,您将学习清理代码。祝你好运!
    猜你喜欢
    • 2011-11-03
    • 1970-01-01
    • 1970-01-01
    • 2019-04-23
    • 1970-01-01
    • 2019-06-15
    • 1970-01-01
    • 2021-01-09
    • 1970-01-01
    相关资源
    最近更新 更多