2013-08-07 212 views
22

我希望我的页面具有从上到下流动的渐变背景。我希望背景的行为像一个固定的图像,因为渐变从当前浏览器视口的顶部延伸到底部,并且在您在页面上下滚动时看起来相同。换句话说,当你滚动时它不会重复。它保持固定。使用css修复渐变背景

所以,我想是这样的:

enter image description here

和滚动到你看到这 enter image description here

注意梯度看起来完全在页面的底部相同的情况下后它在顶部。它从全黄到全红。

最好实际上,我能够做的就是具有梯度跨越整个页面的内容,而不只是可视部分的,就像这样:

enter image description here

和底部看起来是这样的: enter image description here

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

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

+0

你提到的”最好的,我实际上能够做的是让渐变横跨整个连续而不仅仅是可见部分。“你是怎么做到的?这正是我需要的。” – RockPaperLizard

回答

59

如果你想使用CSS3渐变做到这一点,请尝试添加以下内容到选择器。

因此,例如,如果您将渐变应用于#background,则将其添加到CSS渐变之后。 重要:您必须在后台属性之后添加此项。

background-attachment: fixed;

w3schools.org: CSS background-attachment property

你的整个代码可能看起来像:

#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; 
} 
+1

钉牢它,很好的工作 – d512

+6

重要提示:您必须在后台属性后添加 - 完全 –

+1

还值得注意的是,在Firefox(以及其他浏览器)上,“background-attachment”的默认行为我发现即使添加'!important',当后面的元素设置一个基本简单的'background-color:',这是* unsetting *所有其他背景属性,包括'background-attachment'。 – Martin

2
html { 
    height: 100%; 
    /* fallback */ 
    background-color: #1a82f7; 
    background: url(images/linear_bg_2.png); 
    background-repeat: repeat-x; 

    /* Safari 4-5, Chrome 1-9 */ 
    background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#1a82f7), to(#2F2727)); 

    /* Safari 5.1, Chrome 10+ */ 
    background: -webkit-linear-gradient(top, #2F2727, #1a82f7); 

    /* Firefox 3.6+ */ 
    background: -moz-linear-gradient(top, #2F2727, #1a82f7); 

    /* IE 10 */ 
    background: -ms-linear-gradient(top, #2F2727, #1a82f7); 

    /* Opera 11.10+ */ 
    background: -o-linear-gradient(top, #2F2727, #1a82f7); 
} 

http://css-tricks.com/examples/CSS3Gradient/
http://css-tricks.com/css3-gradients/

根据什么浏览器,你的支持,你可能会或可能不希望图像回退。如果不是,则可能需要包含filter-ms-filter语法,以允许使用IE 6-8。即使没有这个或一个图像,它将回退到background-color

+0

我希望渐变保持固定在原位,所以即使你滚动它也不会改变,使用这段代码,当你滚动时,渐变会重复。 – d512

-4

这样做(与实际图像)的另一种方法:

body { 
    background-attachment: local; // or 'fixed' here 
    background-image: url(fancy.jpg); 
    background-size: 100% 100%; 
    overflow:auto; 
    box-sizing:border-box; 
    width:100%; 
    height:100%; 
    margin:0; 
}