【发布时间】: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 实现它,请告诉我。否则我可能会在此期间继续这样做。
【问题讨论】: