2013-08-07 120 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; 
}