skip to Main Content

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.

2

Answers


  1. 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>
    Login or Signup to reply.
  2. Your code was fine but you are facing the background propagation to the html element. Add any background-color to html to fix this and you don’t need to set background-repeat or background-size or background-color to the body element

    document.addEventListener('DOMContentLoaded', () => {
      const p = document.getElementsByTagName('p')[0];
    
      for (let i = 0; i < 400; i++) {
        document.body.appendChild(p.cloneNode(true));
      }
    
    });
    html {
      height: 100%;
      background: #fff; /* added this */
    }
    
    body {
      margin: 0;
      min-height: 100%;
      background: linear-gradient(#F00, #0F0, #00F, #F00 3000px);
    }
    <p>Long line test</p>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search