Search code examples
htmlcssbackgroundgradientvisual-glitch

Glitchy CSS dynamic linear-gradient on scroll


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.


Solution

  • 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.