Optimization of scrolling performance with parallax effect

时间:2017-08-05 11:22:25

标签: html css sass parallax

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;
}

1 个答案:

答案 0 :(得分:1)

从您的尝试和@MrLister建议回答问题:

如前所述,在评论流程中丢失,您错过.lower-section的背景隐藏上一个。{/ p>

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>