Search code examples
htmlcssgradient

Stop linear gradient after certain height


I'm trying to add a gradient to my background using CSS. I want this gradient to not be 'fixed', but scroll with the page. For very tall pages, I just want the gradient to end.

This is my CSS:

body {
  min-height: 100%;
  background-color: #F00;
  background-repeat: no-repeat;
  background: linear-gradient(
    180deg,
    #F00 0px,
    #0F0,
    #00F,
    #F00 3000px
  )
}

The problem is that when I scroll down, after the page fold the gradient starts over. On my 1200px height screen, it never turns blue.

My goal is for the gradient to render once and if the page is larger than the gradient (lets say 3000px) for it to just be #F00 forever. No-repeat had no effect.

Codepen for reference.


Solution

  • You can set background-image and background-color separately.

    document.addEventListener('DOMContentLoaded', () => {
      const p = document.getElementsByTagName('p')[0];
    
      console.log(p)
      for (let i = 0; i < 1000; i++) {
        document.body.appendChild(p.cloneNode(true));
      }
    
    });
    body {
      min-height: 100%;
      background-color: #F00;
      background-repeat: no-repeat;
      background-image: linear-gradient(180deg, #F00 0px, #0F0, #00F, #F00 3000px);
      background-size: 100% 3000px;
    }
    <p>Long line test</p>