Search code examples
htmlcsssassparallax

Optimization of scrolling performance with parallax effect


I have a page with two sections which are stacked over each other. The upper section has a background image with a fixed position to create a parallax effect. Because I had massive performance issues while scrolling I had to change the layout.

From this:

.upper-section {

    height: 100vh;

    background: url("./img/background.png") no-repeat fixed;
    background-size: cover;
}

.lower-section { 
    height: 100vh;
    ...
}

to this:

.upper-section {

    height: 100vh;

    overflow: hidden; // added for pseudo-element
    position: relative; // added for pseudo-element

    &::before {
        content: ' ';
        display: block;
        position: fixed; // instead of background-attachment
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        background: url("./img/background.png") no-repeat fixed;
        background-size: cover;
        will-change: transform; // creates a new paint layer
        z-index: -1;
    }
}

to put the background in it's own container. My problem is that i the background image container is not inheriting the height of the upper-section container and covers the lower section too. If i change position: fixed; to position: absolute; I get the same performance issue as before. Any idea how to fix this issue?

UPDATE 1

To all future readers: I fixed my problem by setting the background of the lower section to white:

.lower-section { 
    height: 100vh;
    background: white;
}

Solution

  • From your attempt and advised from @MrLister to give an answer to the question:

    As commented earlier and lost in the flow of comments , you were missing a background on .lower-section to hide previous one(s).

    html,
    body {
      margin: 0
    }
    
    .upper-section {
      height: 100vh;
      overflow: hidden;
      position: relative;
    }
    
    .upper-section::before {
      content: ' '; 
      position: fixed; 
      width: 100%;
      height: 100%;
      top: 0;
      left: 0;
      background: url("http://lorempixel.com/700/700") no-repeat fixed;
      background-size: cover;
      will-change: transform;  
      z-index: -1;
    }
    
    .lower-section {
      height: 100vh;
      background: white;
    }
    <div class="upper-section">
      Upper section
    </div>
    
    <div class="lower-section">
      Lower section
    </div>