【问题标题】:Prevent DIV from scrolling away horizontally (sticky) but allow vertical scroll防止 DIV 水平滚动(粘性)但允许垂直滚动
【发布时间】:2018-10-03 02:09:16
【问题描述】:

是否可以防止元素水平滚动,但允许它与页面内容的其余部分一起垂直滚动?这有点难以描述,所以让我举个例子:

HTML:

<nav>Side Nav</nav>
<header>Header</header>
<main> 
   <h1>Main Content</h1>
   <div class="wideContainer">
      Some wide and tall container
   </div>
</main>

CSS:

nav {
  position: fixed;
  width: 150px;
  height: 100vh;
}
header {
  height: 100px;
  padding-left: 150px;
}
main {
  padding-left: 150px;
}
.wideContainer {
  width: 2000px;
  height: 1000px;
}

https://jsfiddle.net/hg2zmu1o/7/

如您所见,左列是固定的。当您垂直滚动时,标题会滚动。这是对的。但是当main 区域中有一些宽的内容时,它会进行水平页面滚动(这很好)。但是,当水平滚动时,标题也会移动到侧导航列的后面。

我怎样才能让它保持水平?

我尝试使用position:sticky,但没有成功。

position: sticky;
left: 150px;

请记住,我不想在整个标题上使用position:fixed,因为那样它就不会随着页面的其余部分垂直滚动。

jsfiddle 说明了问题。

编辑:

找到了 this example,它展示了我所追求的行为。它虽然使用 JS,但我希望避免这种情况。

$(window).scroll(function(){
    $('#header').css({
        'left': $(this).scrollLeft() + 15 
         //Why this 15, because in the CSS, we have set left 15, so as we scroll, we would want this to remain at 15px left
    });
});

如果有人知道如何使用纯 CSS 实现它,请告诉我。否则我可能会在此期间继续这样做。

【问题讨论】:

    标签: html css scroll sticky


    【解决方案1】:

    只需将 overflow-x 添加到您的 CSS。

    body {
      padding: 0;
      margin: 0;
      overflow-x:hidden;
    }
    nav {
      position: fixed;
      width: 150px;
      background-color: gray;
      height: 100vh;
    }
    header {
      height: 100px;
      background-color: silver;
      padding-left: 150px;
    }
    main {
      padding-left: 150px;
    }
    .wideContainer {
      width: 100%;
      height: 1000px;
      background-color: turquoise;
    }
    <nav>Side Nav</nav>
    <header>Header</header>
    <main> 
     <h1>Main Content</h1>
     <div class="wideContainer">
       Some wide and tall container
     </div>
    </main>

    这是你一直在寻找的吗?

    我还制作了thisthis

    希望对你有帮助!

    【讨论】:

    • 感谢您的帮助,但很抱歉,不,这不是我要找的。 overflow-x: hidden 隐藏任何溢出的内容,我需要水平滚动才能看到它。 “wideContainer”中的东西不能被包装。想象它是一个包含许多列的大型数据表,用户必须水平滚动才能看到它。但是,在水平滚动查看主区域中的数据时,标题应保持在原位。但是,如果您垂直滚动,它应该向上/向下滚动(因此您的带有fixed 标头的解决方案之一不适用于此)。
    • this link了吗?您可以水平浏览它,但标题保持在其位置。如果这不是您想要的,您能否发布您所期望的页面/网站图片或链接?
    • 我做到了。正如我已经说过的,该示例中的标题即使在垂直滚动时也保持固定。我的要求是在向上/向下滚动时不要修复标题。只有左/右。我在上面链接到a solution that uses JS 的帖子中发布了一个编辑。在此期间我将使用它,但我仍然对是否有纯 CSS 解决方案感兴趣。
    • 我刚刚想到了this。猜猜这是我最好的镜头。希望我做对了!
    • 再次感谢,但恐怕它不是很有用,因为用户直到到达主要内容的底部(可能低于视口)。到达底部后,您可以水平滚动(并且标题会保留,是的),但是您必须向上滚动才能看到滚动的主要内容。我可能只需要继续使用我找到的基于 JS 的解决方案。
    猜你喜欢
    • 2014-05-05
    • 1970-01-01
    • 2023-01-17
    • 1970-01-01
    • 1970-01-01
    • 2019-04-23
    • 2020-01-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多