6

I tested it on different up-to-date browsers, therefore it can't be compatibility problem. I'm using create-react-app with styled components, here's my code:

import React, { Component } from 'react';
import styled, { createGlobalStyle } from 'styled-components';

const GlobalStyle = createGlobalStyle`
@import url('https://fonts.googleapis.com/css?family=Merriweather|Oleo+Script');
`

const Wrapper = styled.div`
  scroll-snap-type: y mandatory;
  display: flex;
  flex-direction: column;
  font-size: 16px;
`

const Home = styled.div`
  scroll-snap-align: center;
  height: 100vh;
  background-color: yellow;
  display: flex;
  flex-direction: row;
`

const Menu = styled.div`
  scroll-snap-align: center;
  height: 100vh;
  background-color: blue;
  display: grid;
`

const Speciality = styled.div`
  scroll-snap-align: center;
  height: 100vh;
  background-color: green;
`

class App extends Component {

  render() {
    return (
      <Wrapper>
        <GlobalStyle />
        <Home />
        <Menu />
        <Speciality />
      </Wrapper>
    );
  }
}

export default App;

It doesn't do anything when I'm scrolling, I've tried almost anything. It won't work without styled-components either.

EDIT: I copied my code to codesandbox: https://codesandbox.io/s/72jmn1p1w1

b4l4g3
  • 61
  • 2
  • 3
  • it scrolls ok in chrome - what exactly doesn't it do? – Mikkel Mar 27 '19 at 23:42
  • @Mikkel it should scroll like this: https://i.imgur.com/vMW8ALh.gif – b4l4g3 Mar 29 '19 at 08:43
  • I'm also having trouble making the css scroll snap with styled components within React. I've integrated the same code as https://snap.glitch.me/product.html but could not make work. – Pat M Nov 28 '19 at 19:19

3 Answers3

9

Rather than apply scroll-snap-type: y mandatory to the parent div, try applying it to html:

html {scroll-snap-type: y mandatory}

secret-sauce
  • 91
  • 1
  • 2
5

In your code sandbox I`ve replaced the Wrapper element code with the following to make it work:

const Wrapper = styled.div`
  scroll-snap-type: y mandatory;
  max-height: 100vh;
  overflow-y: scroll;
`;

This fixes a few issues:

  • Explicitly stating the height of the wrapper, therefore creating a "window" for the elements inside to snap to;
  • Setting overflow to scroll or auto, because child elements need to be "hidden" inside the wrapper and visible only through scrolling for scroll-snap to work (and make sense);
  • Removing display: flex, as it may force children to adjust their width or height in order to fit the container, which is the opposite of what we want--we need child elements to be hidden from view because of scroll height/width. Alternatively, you could work with flex: 1 on child elements to prevent them from resizing, depending on your use case.
0

I had some problems with the scroll-snap too.

For me this doesn't work without the overflow-y: scroll, try to put this on your Wrapper.

Anton Krug
  • 1,555
  • 2
  • 19
  • 32