Search code examples
htmlcsssnap

How to correctly setup Vertical scroll snap css


I want to create a website. with multiple sections with a width of 100vw and a height of 100vh.I also want a mandatory y (vertical) snap for these sections. I have checked out many tutorials, But my code doesn't seem to work. Any help is highly appreciated.

Current code

body {
  width: 100%;
  margin: 0;
  background-color: white;
}

body .content {
  width: 100vw;
  height: 100%;
  scroll-snap-type: mandatory;
  scroll-snap-points-y: repeat(300px);
  scroll-snap-type: y mandatory;
}

body .content section {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100vw;
  height: 100vh;
  border: 1px solid black;
  scroll-snap-align: start;
}
<div class='content'>
  <section>1</section>
  <section>2</section>
  <section>3</section>
  <section>4</section>
</div>


Solution

  • Just reading the Mozilla docs on this makes it seem like this feature is highly inconsistent between browsers, but following their guide I managed to make your snippet work with these changes:

    body .content {
      height: 100vh; /* was 100% */
      overflow: auto; /* added */
    }
    

    body {
      width: 100%;
      margin: 0;
      background-color: white;
    }
    
    body .content {
      width: 100vw;
      height: 100vh;
      scroll-snap-points-y: repeat(300px);
      scroll-snap-type: y mandatory;
      scroll-snap-type: mandatory;
      overflow: auto;
    }
    
    body .content section {
      display: flex;
      justify-content: center;
      align-items: center;
      width: 100vw;
      height: 100vh;
      border: 1px solid black;
      scroll-snap-align: start;
    }
    <div class='content'>
      <section>1</section>
      <section>2</section>
      <section>3</section>
      <section>4</section>
    </div>