2012-04-03 71 views
0

我有一個div和它裏面的圖片作爲背景:CSS定位的麻煩

<div id="background"> 
    <img src="background.png" class="stretch" alt="" /> 
    <div class="header"> 
    <span>header</span> 
    </div> 
    <div class="picture"> 
    <img src="pic" alt="" /> 
    </div> 
</div> 

下面CSS:

#background { 
    width: 100%; 
    height: 100%; 
    position: absolute; 
    left: 0px; 
    top: 0px; 
    z-index: 0; 
} 

.stretch { 
    width:100%; 
    height:100%; 
} 

.header { 
    position: absolute; 
    left: 12px; 
    top: 18px; 
    font-family: Arial; 
    font-size: 14pt; 
    color: #3A4549; 
    margin-bottom: 
} 

這裏有一個小提琴:http://jsfiddle.net/3j7vk/

我怎麼能在標題下面添加圖像而不指定絕對位置? 現在它在背景圖像下。謝謝!

+0

你能製作一個[jsfiddle](http://jsfiddle.net)嗎?你可以使用[lorempixel](http://lorempixel.com)或[placekitten](http://placekitten.com)的圖片 – JKirchartz 2012-04-03 13:04:30

+0

http://jsfiddle.net/3j7vk/ – scorpion 2012-04-03 13:10:23

回答

0

是否有任何理由不只是將圖像作爲背景添加到div中?

#background { 
    background: url(background.png) no-repeat; 
    background-size: cover; 
    /*other rules*/ 
    } 

如果圖像只是一個背景,它應該不會出現在標記中。

請參閱本頁上的background-size property

+0

我不能這樣做,因爲我需要垂直拉伸圖像 – scorpion 2012-04-03 13:14:54

+0

這就是背景大小的屬性。 – chipcullen 2012-04-03 13:15:19

0

奇怪的是,你沒有使用CSS的背景圖像屬性,但回答你的問題,你可以給元素z-index指定它們的順序,並使它們顯示在彼此之上。它只有被指定的位置屬性時的作品,而不是使其成爲絕對的,使其相對:

.stretch { 
    width:100%; 
    height:100%; 
    position: relative; 
    z-index: 1; 
} 

然後給它自己的你.header的z-index:

z-index: 2; 

但要說實話,在我看來,使用CSS的背景屬性將是更好的選擇。

+0

.container { background:url(box_bg.png)重複滾動0 0透明; background-size:cover; }我現在有這個,但它根本不顯示圖像 – scorpion 2012-04-03 13:21:33

+0

圖像的路徑是否正確?根據你的評論,圖像應該與CSS在同一個文件夾中。 – cchana 2012-04-03 13:27:29

+0

是的,它在同一個文件夾中。問題是我有一個png圖像,我需要重複X,但我也必須垂直拉伸 – scorpion 2012-04-03 13:30:09

0

好吧,如果你想使用img作爲你的背景,你能做到這一點,像這樣:

<div id="background"> 
    <img src="http://placekitten.com/g/600/600/" class="stretch" alt="" /> 
    <div id="container"> 
     <div class="header"> 
      <span>header</span> 
     </div>  
     <div class="pic"> 
      <img src="http://lorempixel.com/200/200/" alt="" /> 
     </div> 
    </div> 
</div>​ 

CSS:

#container { 
    position:absolute; 
    top:0; 
    left:0; 
} 
#background, .stretch, #container { 
    width: 100%; 
    height: 100%; 
} 
.header { 
    font-family: Arial; 
    font-size: 14pt; 
    color: #3A4549; 
    margin-bottom: 
} 
.pic 
{ 
    height: 114px; 
}​ 

小提琴:http://jsfiddle.net/JKirchartz/SrvyD/

這就是你的容器流中的一切就像一個普通的html文檔,你不必定位一切。

+0

事實上,這就是我一直在尋找的,我也會投這個答案,但我沒有足夠的聲譽。也謝謝你! – scorpion 2012-04-03 13:32:48