Is it possible to prevent an element from scrolling away horizontally, but allow it to scroll vertically with the rest of the page content? It's a little hard to describe, so let me show an example:
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/
As you can see, the left column is fixed. The header scrolls away when you scroll vertically. This is correct. But when there is some wide content in the main
region, it makes a horizontal page scroll (which is fine). However, when scrolling horizontally, the header also moves behind the side nav column.
How can I make it stay horizontally?
I tried using position:sticky
but without success.
position: sticky;
left: 150px;
Keep in mind, I don't want to do position:fixed
on the whole header, because then it wouldn't scroll vertically with the rest of the page.
The jsfiddle illustrates the problem.
EDIT:
Found this example that demonstrates the behavior I'm after. It uses JS though, which I was hoping to avoid.
$(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
});
});
If anyone knows how to achieve it with pure CSS let me know. Otherwise I may go with this in the meantime.