Glitchy CSS dynamic linear-gradient on scroll

696 views Asked by At

I've noticed that CSS linear-gradient as a dynamic background (using keyframes) seems to look glitchy if you scroll really quickly along the page. For instance, here, if you grab the scroll bar and scroll up and down really quickly, you can see the white underneath. Appears to be something to do with how the gradient redraws as more of the page is revealed or... I've tried searching all over the place, but haven't been able to find anything specific to this -- any ideas? The relevant CSS is:

body {
    background: linear-gradient(angle, some colours);
    background-size: 200% 200%;
    animation: gradient 15s ease infinite;
}

@keyframes gradient {
    0% {
        background-position: 0% 50%;
    }
    50% {
        background-position: 100% 50%;
    }
    100% {
        background-position: 0% 50%;
    }
}

I wonder if the background has to be fixed somehow as some kind of "image" so that the browser doesn't have to redraw the gradient on scroll.

2

There are 2 answers

1
Agénor Debriat On BEST ANSWER

Simply do your styling on a pseudo ::before element instead of doing it directly on body, so you can use position: fixed.

body::before {
  content: "";
  position: fixed;
  width: 100%;
  height: 100%;
  z-index: -1;
  background: linear-gradient(240deg, #567EB9 0%, #B29ACA 50%, #B29ACA 70%, #F9839B 95%, #e6b394 100%);
  background-size: 200% 200%;
  animation: gradient 15s ease infinite;
}

It might not be the best solution, but it works.

0
Temani Afif On

Consider a fixed element where you apply a translation:

html::before {
  content: "";
  position: fixed;
  top: 0;
  left: 0;
  width: 200%;
  height: 100%;
  background: linear-gradient(60deg, red, blue, green);
  animation: gradient 3s linear infinite alternate;
}

@keyframes gradient {
  100% {
    transform: translateX(-50%);
  }
}