2015-09-26 107 views
0

我有一個用作頁面背景的div,其他div顯示在其上。CSS:使div滑過另一個div(即使用div作爲背景)

但是當用戶滾動時,背景div也會滾動。我希望在內容div滾動時修復它。

這是我的實際代碼:

#background { 
    z-index: 1; 
    width: 100%; 
    height: 100vh; 
    position: fixed; 
} 
#content { 
    z-index: 99; 
    position: absolute; 
    top: 2em; 
    padding: 1em 1em; 
    width: 100%; 
} 

才能做到這一點?謝謝

+0

,可以在運行中撥弄 –

回答

2

當使用position: fixed您還需要爲元素的位置指定值。

一個證明這一點:

HTML:

<div id="background"></div> 
<div id="content"> 
    This is the content 
</div> 

CSS:

#background { 
    z-index: 1; 
    width: 100%; 
    height: 100%; 
    position: fixed; 
    top: 0; 
    left: 0; 
    background-image: url(https://wallpaperscraft.com/image/metal_lines_stripes_light_shiny_silver_18401_1920x1080.jpg); 
} 
#content { 
    z-index: 99; 
    position: absolute; 
    top: 2em; 
    padding: 1em 1em; 
    width: 100%; 
    color: blue; 
    font-size: 300%; 
    height: 400%; 
} 
+0

問題是,背景div不是圖像,而是來自Google地圖的地圖。所以我不能設置背景圖片。 – FrCr

+0

@FrCr你在問題中沒有這麼說。那麼你如何參考該地圖呢?爲什麼你不能簡單地添加一個img標籤到背景div或類似的?背景圖像只是一個例子。它是固定的div,這就是你所問的。 – arkascha

+0

你是對的,我剛纔發現這對我來說並不適用,因爲我使用的是框架,而不是代碼本身的問題。現在我已經修復了它,感謝您的代碼以及框架所需的一些修改。謝謝! – FrCr

1

你可以看到演示頁:

body, html, main { 
    /* important */ 
    height: 100%; 
} 

.cd-fixed-bg { 
    min-height: 100%; 
    background-size: cover; 
    background-attachment: fixed; 
    background-repeat: no-repeat; 
    background-position: center center; 
} 

.cd-fixed-bg.cd-bg-1 { 
    background-image: url("http://farm5.static.flickr.com/4056/4228935406_93ff14c971.jpg"); 
} 
.cd-fixed-bg.cd-bg-2 { 
    background-image: url("http://farm5.static.flickr.com/4056/4228935406_93ff14c971.jpg"); 
} 
.cd-fixed-bg.cd-bg-3 { 
    background-image: url("http://farm5.static.flickr.com/4056/4228935406_93ff14c971.jpg"); 
} 
.cd-fixed-bg.cd-bg-4 { 
    background-image: url("http://farm5.static.flickr.com/4056/4228935406_93ff14c971.jpg"); 
} 

.cd-scrolling-bg { 
    min-height: 100%; 
} 

HERE MY DEMO

+0

的代碼將是有益的,如果你解釋你除了做了什麼代碼轉儲 –

+0

問題是,通過背景div不是圖像,而是來自Google地圖的地圖。所以我不能設置背景圖片。 – FrCr