When I have a .sections
container with several .section
elements inside, and setup scroll-snap, it will ONLY work if I give the section a fixed height of 100vh. Without the height, the scroll-snap will not work. This is fine, except without the fixed height, scrollTo
works correctly, and when I add the height to the section, scrollTo
no longer works.
Here is an example. You can comment out the height: 100vh;
line in the .section
CSS and see that clicking anywhere will scroll down to section #3, but with the height turned on, it won't scroll.
I have tried to console.log
the position it is scrolling to and it is correct, but the scroll never actually takes place. Any ideas as to why this is not behaving the way I would like?
NOTE: I am seeing this behavior in the latest Chrome. I have not tested another browser.
// Click on document to scroll to section 3
document.body.onclick = function() {
console.log('SCROLLING...');
const el = document.getElementById('s3');
const pos = el.getBoundingClientRect();
window.scrollTo(0, pos.top);
}
* {
box-sizing: border-box;
}
html,
body {
margin: 0;
padding: 0;
}
.sections {
overflow-y: scroll;
scroll-snap-type: y mandatory;
/**
* Adding the below line breaks scrollto, removing
* it breaks scroll-snap....
*/
height: 100vh;
}
.section {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 100vh;
overflow: hidden;
position: relative;
border: 5px solid deeppink;
font-size: 30px;
font-weight: bold;
scroll-snap-align: center;
}
<html>
<body>
<div class="sections">
<div class="section" id="s1">SECTION 1</div>
<div class="section" id="s2">SECTION 2</div>
<div class="section" id="s3">SECTION 3</div>
<div class="section" id="s4">SECTION 4</div>
<div class="section" id="s5">SECTION 5</div>
</div>
</body>
</html>
.sections
when making the height:100vh and not the window (document.querySelector('.sections').scrollTo(0, pos.top);
should do it I guess) – Housemaid