2014-04-01 70 views
4

我有一個可變大小的容器,它有一個重複的背景圖塊,可以在任意寬度上伸展以填充容器。我需要容器的高度,使它始終是1瓦的高度的倍數 - 這樣我就可以無縫地將容器的底部與下一個容器的bg圖像的「結束」瓦片對齊。 我試圖用jQuery來做,但我的代碼不工作...將重複背景圖像與容器底部的非重複背景圖像對齊

注意:重複背景必須從TOP開始,因爲上面有另一塊它加入(所以解決方案來設置從底部重複的背景圖塊在這種情況下不適用 - 只會在頂部將其折斷) 我需要JavaScript才能正常工作,而不是僅更改CSS。

小提琴:http://jsfiddle.net/nRe7R/1/

這裏是JS:

function seamlessBottomBg() { 
    var container = $('#container1'); 
    var bgTileAspectRatio = 65/1163; 
    var tileWidth = container.outerWidth(); 
    var tileHeight = tileWidth * bgTileAspectRatio; 
    //calculate how many px high the 'cutoff' last bg tile is, if there is a cutoff part 
    var cutOffTileHeight = container.outerHeight() % tileHeight; 
    if(cutOffTileHeight !== 0) { 
    container.css('padding-bottom', tileHeight-cutOffTileHeight+1+'px'); 
     } 
    } 
seamlessBottomBg(); 

和CSS:

#container1 { 
    background-size: contain; 
    background-image: url(http://img.photobucket.com/albums/v488/fishygirl/paper-repeating_zps52e98fe2.jpg); 
    background-repeat: repeat-y; 
    width: 80%; 
    margin: 0 auto; 
    padding: 3em 10% 0; 
    max-width: 1200px; 
} 
#container2 { 
    background-size: contain; 
    background-image: url(http://img.photobucket.com/albums/v488/fishygirl/paper-bg-bottom_zps441e1bc3.jpg); 
    background-repeat: no-repeat; 
    width: 80%; 
    margin: 0 auto; 
    padding: 3em 10% 0; 
    max-width: 1200px; 
} 
+0

所以希望我的理解它。 :)爲什麼不剪切圖像,你只有1行,然後重複它。 – user1551496

+0

因爲紙張的邊上還有孔,所以還需要在那裏。 – b4rbika

回答

1

我相信,如果你設置的背景圖像bottom就會重複向上。不知道這是你想要的,但這裏有一個fiddle

#container1 { 
    background-size: contain; 
    background-image: url(http://img.photobucket.com/albums/v488/fishygirl/paper-repeating_zps52e98fe2.jpg); 
    background-repeat: repeat-y; 
    background-position: bottom; 
    width: 80%; 
    margin: 0 auto; 
    padding: 3em 10% 0; 
    max-width: 1200px; 
} 
+0

它必須從頂部重複,因爲還有另一張紙在頂部加入(我不認爲將它添加到小提琴中,對不起)。我正在使用你放在頂端的規則。 – b4rbika

1

DEMO(嘗試調整)

添加下列規則:

#container1 { 
    background-size:center bottom; 
} 

#container2 { 
    background-size:center top; 
} 

@media (min-width:1024px) { /* 1024px is based on the image's width */ 
    #container2 { 
     background-size: cover; 
    } 
} 
+0

它必須從頂部重複而不是底部,因爲在頂部還有另一張撕碎的紙片(我沒有想到將它添加到小提琴中,對不起)。我正在使用你放在頂端的規則。 – b4rbika

+0

你不能期望頂部和底部對齊。作爲一種解決方法,您可以編輯底部圖像,以便向右出現的部分不存在。這將使所有的東西看起來一致。 – kei

+0

我不期望它用純CSS做到這一點,你看過JS嗎?我正在嘗試將重複圖塊的容器高度設置爲該圖塊高度在該窗口大小下的精確倍數。或者我的邏輯有問題嗎? – b4rbika