本文介绍了使用 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:

滚动到底部后你会看到这个

and after scrolling to the bottom you see this

请注意,页面底部的渐变看起来与顶部完全相同.它从全黄变为全红.

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:

底部看起来像这样:

请注意,渐变跨越内容的整个长度,而不仅仅是当前可见的内容.因此,在页面顶部您看到的大部分是黄色,而在页面底部您看到的大部分是红色.

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.

我想我可以使用在 y 平面中拉伸并在 x 平面中重复的图像来解决这个问题,但我宁愿不这样做,因为如果可能的话,因为拉伸图像可能会导致块状、非颗粒状的渐变.这可以仅使用 CSS 动态完成吗?

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?

推荐答案

如果您希望使用 CSS3 渐变,请尝试使用 背景附件属性

If you wish to do this using CSS3 gradients, try using the background-attachment property

例如,如果您将渐变应用到 #background,则将其添加到 CSS 渐变之后.

For example, if you are applying your gradients to #background, then add this after the CSS gradient.

背景附件:固定;

注意:您必须在背景属性之后添加background-attachment .

您的整个代码可能如下所示:

Your entire code might look like this:

#background {
  background: #1e5799;
  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:    -moz-linear-gradient(top,  #1e5799 0%, #7db9e8 100%);
  background:     -ms-linear-gradient(top,  #1e5799 0%, #7db9e8 100%);
  background:      -o-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;
}

这篇关于使用 css 修复渐变背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-28 16:36
查看更多