'Scrolling without moving main content

I want to be able to scroll a div without really moving the page contents (to trigger animations). My idea was to use position fixed on the main content of the page (the main content is only 100vh of height) and then create a secondary div that has absolute position and scales through the whole page.

Here my files:

<div className="App">
   <div className="test">
      Hello
   </div>

   <div className="scrollArea" ref={scrollArea}/>
</div>

And my css

html, body {
  width: 100%;
  height: 100%;
}

body {
  padding: 0;
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
    sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.App {
  font-family: sans-serif;
  text-align: center;
  height: 100%;
  width: 100%;
}

.test{
  width: 100vw;
  height: 100vh;
  position: fixed;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  font-size: 5vh;
}

.scrollArea{
  position: absolute;
  width: 100vw;
  height: 200vw;
  z-index: 99;
  pointer-events: none;
}

This works. I can scroll without moving my content inside of my "test" div. For some reason however the scrollbar gets attached to body instead of the "App" div. Why does it behave like that? If i add an onScroll event to my "App" div i don't register any changes. Can someone explain how to change this behavior? I tried using overflow: hidden on body and html, but then the scrollbar didn't work anymore at all.



Solution 1:[1]

Are you trying to hide the scrollbar?

html, body {
  width: 100%;
  height: 100%;
  -ms-overflow-style: none;  /* IE and Edge */
  scrollbar-width: none;  /* Firefox */
}
/* Hide scrollbar for Chrome, Safari and Opera */
html::-webkit-scrollbar ,body::-webkit-scrollbar {
  display: none;
}

body {
  padding: 0;
  margin: 0;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',
    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',
    sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
}

.App {
  font-family: sans-serif;
  text-align: center;
  height: 100%;
  width: 100%;
}

.test{
  width: 100vw;
  height: 100vh;
  position: fixed;
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  font-size: 5vh;
}

.scrollArea{
  position: absolute;
  width: 100vw;
  height: 200vh;
  z-index: 99;
  pointer-events: none;
  overflow-y: scroll;
}
<div class="App">
   <div class="test">
      Hello
   </div>

<div class="scrollArea" ref={scrollArea}>
  <p>
  1
  </p><p>
  2
  </p><p>
  3
  </p>
  
</div>
</div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 knicholas