Search code examples
javascriptcssreactjsscrollnext.js

Vertical scroll snap doesn't work with Next.js


I'm trying to get working this scroll snap css feature in my Next.js project. Haven't done such a feature yet. The article of reference is this one. After applying scroll-snap-type to the parent and scroll-snap-align to children (start/center... all of them) my scroll behave the ordinary way. Can't get my head around what I'm missing.

Here's index.js

import React from 'react'
import '../index.css'

import Carusel from '../components/carusel'

const Home = () => (
  <div>
    <Carusel />
  </div>
)

export default Home

Here's carusel.js

import React, { Component } from 'react'

class Carusel extends Component {
  render() {
    return (
      <section className='container'>
        <h1 className='child' >Slide 1</h1>
        <h1 className='child' >Slide 2</h1>
        <h1 className='child' >Slide 3</h1>
        <h1 className='child' >Slide 4</h1>
        <h1 className='child' >Slide 5</h1>
        <style jsx>{`
          .container {
            width: calc(100vw-(100vw-100%));
            height: 100vh;
            text-align: center;
            scroll-snap-type: y proximity;
            scroll-padding: 10px;
          }
          .child {
            height: 100%;
            scroll-snap-align: center;
          }
          .child :nth-child(odd) {
            background-color: red;
          }
          .child :nth-child(even) {
            background-color: green;
          }
      `}</style>
      </section>
    )
  }
}

export default Carusel

Here's index.css

html {
  overflow-y: scroll;
}

Solution

  • Most likely because you are scrolling the body and not the 'container'

    .container {
      width: calc(100vw - (100vw - 100%));
      height: 100vh;
      text-align: center;
      scroll-snap-type: y mandatory;
      scroll-padding: 10px;
      overflow-y: scroll;
    }
    
    .child {
      height: 100%;
      scroll-snap-align: center;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    .child :nth-child(odd) {
      background-color: red;
    }
    
    .child :nth-child(even) {
      background-color: green;
    }
    <section class='container'>
      <h1 class='child'>Slide 1</h1>
      <h1 class='child'>Slide 2</h1>
      <h1 class='child'>Slide 3</h1>
      <h1 class='child'>Slide 4</h1>
      <h1 class='child'>Slide 5</h1>
    </section>

    PS: scroll snap isn't supported in Firefox