2015-12-14 41 views
4

我有一個背景圖像,其中第一行像素是純色(它是風景的照片)。這個想法應該是在頁面的底部,然後在它上面的一個CSS漸變,它將從頁面的頂部延伸,停在圖像的高度。有很多教程展示瞭如何疊加/疊加漸變,但他們都假設你想要一個完整的頁面漸變或者將漸變疊加在背景圖像的頂部。在背景圖像頂部垂直堆疊css漸變(不覆蓋)

我現在擁有的是:

background: rgba(30, 53, 192, 1); 

background: url("myimage.jpg") no-repeat center bottom, -moz-linear-gradient(top, #000 0%, #1E35C0 100%); 
background: url("myimage.jpg") no-repeat center bottom, -webkit-gradient(linear, 0% 0%,0% 100%, from(#000), to(#1E35C0)); 
background: url("myimage.jpg") no-repeat center bottom, -webkit-linear-gradient(top, #000 0%,#1E35C0 100%); 
background: url("myimage.jpg") no-repeat center bottom, -o-linear-gradient(top, #000 0%,#1E35C0 100%); 
background: url("myimage.jpg") no-repeat center bottom, -ms-linear-gradient(top, #000 0%,#1E35C0 100%); 
background: url("myimage.jpg") no-repeat center bottom, linear-gradient(top, #000 0%, #1E35C0 100%); 

background-size: contain; 

這有幾乎預期的效果。 CSS漸變效果很好,並且圖像處於正確的位置,但我不知道如何使圖像上方的漸變停留更合適,響應更快。我可以使用百分比,但是再一次,只有當我知道圖像的高度時纔有效。

我知道這可能是相當容易在JavaScript中,但我希望有一個乾淨的CSS方式來做到這一點。

+0

是你正在放置未知的比例('contain'ing)圖像到未知寬度的容器中,所以不能預測其高度在事實問題,你可以以其它方式設置爲背景梯度作爲'背景size'? – myf

+0

我想是這樣,這適用於'身體',所以未知的寬度是瀏覽器窗口。如果我將圖像固定爲特定高度,我認爲這將是微不足道的。圖像是一個風景,所以我想要展開整個頁面的寬度,而不是扭曲,如果我限制了高度,會發生這種情況。 – Josh

+0

如果您知道圖像的寬高比,則可以使用vw單位(視口寬度)進行設置。我會測試一下。 – andi

回答

3

假設你的圖像具有4的縱橫比:在那裏

html, body { 
 
    margin: 0; 
 
    height: 100%; 
 
} 
 
body { 
 
    background-color: #ccc; 
 
    background-image: url("http://ima.gs/transparent/000/000/200%C3%9750-200x50.png") 
 
        , linear-gradient(to top, transparent 25vw, #fff 25vw, #00f 100%); 
 
    background-repeat: no-repeat; 
 
    background-position: center bottom; 
 
    background-size: contain; 
 
}

大衆單元:1(即高度爲寬度的25%),則可以做到這一點漸變意味着視口寬度的百分比。因此,如果背景圖片將拉伸視口的整個寬度,並且其高度爲其寬度的25%,那麼其高度將等於25vw,並且您可以從底部開始25vw的漸變,並在頁面頂部結束。

http://jsfiddle.net/8a5L20h4/

+0

完美地工作,謝謝! – Josh