user1334007 user1334007 - 2 months ago 18
CSS Question

Fixed gradient background with css

I would like for my page to have a gradient background flowing from top to bottom. I want the background to act like a fixed image in that the gradient stretches from the top of the current browser viewport to the bottom and looks the same as you scroll up and down the page. In other words, it does not repeat when you scroll. It stays fixed in place.

So what I want is this:

enter image description here

and after scrolling to the bottom you see this
enter image description here

Notice that the gradient looks exactly the same on the bottom of the page as it does on the top. It goes from full yellow to full red.

The best I'm actually able to do is having the gradient span the entire content of the page instead of just the viewable portion, like this:

enter image description here

and the bottom looks like this:
enter image description here

Notice here that the gradient spans the entire length of the content, not just what is currently visible. So at the top of the page you see mostly yellow and at the bottom of the page you see mostly red.

I suppose I could solve this using an image stretched in the y plane and repeated in the x plane but I'd rather not do this since if possible since stretching the image might leading to a blocky, non granular looking gradient. Can this be done dynamically with just CSS?

Answer

If you wish to do this using CSS3 gradients, try adding the following to the selector.

So for example, if you are applying your gradients to #background, then add this after the CSS gradient. Important: You must add this after the background properties.

background-attachment: fixed;

w3schools.org: CSS background-attachment property

Your entire code could look like:

#background {
  background: #1e5799;
  background: -moz-linear-gradient(top,  #1e5799 0%, #7db9e8 100%);
  background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#1e5799), color-stop(100%,#7db9e8));
  background: -webkit-linear-gradient(top,  #1e5799 0%,#7db9e8 100%);
  background: -o-linear-gradient(top,  #1e5799 0%,#7db9e8 100%);
  background: -ms-linear-gradient(top,  #1e5799 0%,#7db9e8 100%);
  background: linear-gradient(to bottom,  #1e5799 0%,#7db9e8 100%);
  filter: progid:DXImageTransform.Microsoft.gradient( startColorstr='#1e5799', endColorstr='#7db9e8',GradientType=0 );
  background-attachment: fixed;
}
Comments