James Newton
James Newton

Reputation: 7104

Why is overflow-y required for a CSS parallax effect?

I have created a barebones parallax demo. This works fine, as you can see if you run the snippet below. However, it stops working if I remove the following CSS rule:

main {
  overflow-y: auto;
}

Why is it necessary to include a rule for a vertical scrollbar, when there is no need to scroll vertically?

body {
    margin: 0;
  }

  main {
    width:100vw;
    height:100vh;
    perspective: 2px;

    /* overflow-y MUST be set to a certain value for parallax to work
      * WORKS:
      * + auto
      * + hidden
      * + overlay
      * + scroll
      * FAILS:
      * - clip
      * - inherit
      * - initial
      * - revert
      * - unset
      * - visible
    */
    overflow-y: auto;
  }

  div {
    position: absolute;
    top: 0;
    width: 99vw;
    height: 100%;
  }

  div:nth-child(1) {
    left: 0;
    background-color: #900;
  }

  div:nth-child(2) {
    left: 49.5vw;
    background: rgba(0,192,0,0.5);
    height: 80%;
    top: 10%;

    transform: translateZ(1px) scale(0.5);
    z-index: 1;
  }

  div:nth-child(3) {
    left: 99vw;
    background-color: #009;
  }
<body>
    <main>
       <div></div
      ><div></div
      ><div></div>
    </main>
  </body>

Upvotes: 0

Views: 460

Answers (1)

Temani Afif
Temani Afif

Reputation: 273700

Why is it necessary to include a rule for a vertical scrollbar, when there is no need to scroll vertically?

You need to scroll vertically but you need to scroll the main and no the sceen. There is a small trap here because removing the scroll of the main will make the default scroll of the screen to appear and you think both are the same but no. We need to scroll the main because the perspective is defined there.

Reduce the width/height slightly and you will better understand. now if you remove/add overflow you will see that it's different

body {
  margin: 0;
}

main {
  width: 90vw;
  height: 90vh;
  perspective: 2px;
  overflow-y: auto;
}

div {
  position: absolute;
  top: 0;
  width: 99vw;
  height: 100%;
}

div:nth-child(1) {
  left: 0;
  background-color: #900;
}

div:nth-child(2) {
  left: 49.5vw;
  background: rgba(0, 192, 0, 0.5);
  height: 80%;
  top: 10%;
  transform: translateZ(1px) scale(0.5);
  z-index: 1;
}

div:nth-child(3) {
  left: 99vw;
  background-color: #009;
}
<main>
  <div></div>
  <div></div>
  <div></div>
</main>

Basically, the element having the perspective need to have its content scrolling to see the effect.

Upvotes: 1

Related Questions