Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

css scroll snap isn't working on divs in React app

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

like image 785
b4l4g3 Avatar asked Feb 20 '19 11:02

b4l4g3


2 Answers

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

html {scroll-snap-type: y mandatory}

like image 196
secret-sauce Avatar answered Oct 22 '22 02:10

secret-sauce


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.
like image 3
Renan de Freitas Avatar answered Oct 22 '22 04:10

Renan de Freitas