2012-01-29 31 views
0

一直試圖解決這個問題,我在這裏。基本上我有一個有背景的網站。在這個背景下,我有一個居中的圖像,我們稱之爲image1。恰好在image1的頂部,我想繪製image2。所以基本上我有一個背景,我想繪製兩個中心圖像ontop。我稱它們爲centeredImage和overlayImage。在CSS和HTML中定位圖像ontop彼此

謝謝你的幫助! 最好的問候,盧卡斯

這裏是我到目前爲止的代碼:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html> 
<head> 
<style type="text/css" media=screen> 

body{ 
    background-color:#f1e6d0; 
    background-image:url('backgroundPattern.jpg'); 
} 
.containerPage 
{ 
    position:relative; 
    display: block; 
    width:1024; 
    height:1515; 
    margin-top:50px; 
    margin-left:auto; 
    margin-right:auto;  
} 
.overlayImage1 
{ 
    position:absolute; 
    left:0px; 
    top: 0px; 
    z-index: 1; 
} 
.overlayImage2 
{ 
    position:absolute; 
    left:0px; 
    top: 0px; 
    z-index: 2; 
} 

</style> 

<title>A dream within a dream</title> 
</head> 
<body> 


<!-- PAGE BEGINS --> 
<div class= "containerPage"> 

    <!-- BACKGROUND IMAGE --> 
    <img class="overlayImage1" src="column.gif" unselectable="on" height="1515" width="1024"/> 
    <img class="overlayImage2" src="webSite_split_page1.gif" height="1515" width="1024"/> 
    <!-- CONTENT BEGINS --> 
    <!-- LEFT SIDE --> 

</div> 

</body> 
</html> 

回答

1

我明白你現在的樣子。嘗試這個。您將需要調整top值以獲得正確的垂直對齊。

http://jsfiddle.net/frV3D/

body{ 
    background-color:#f1e6d0; 
    background-image:url('backgroundPattern.jpg'); 
} 
.containerPage 
{ 
    position:relative; 
    display: block; 
    width:1024; 
    margin-top:50px; 
    margin-left:auto; 
    margin-right:auto; 

} 

.centeredImage { display: block; margin: 0 auto; } 

.overlayImage { 
    position: absolute; 
    top: 50%; 
    left: 50%; 
    width: 300px; 
    height: 300px; 
    margin-top: -150px; /* Half the height */ 
    margin-left: -150px; /* Half the width */ 
} 
+0

似乎工作正常!謝謝! – 2012-01-29 06:41:19

+0

順便說一句,任何人都有一個很好的解釋,爲什麼50%用於overlayimage?那背後的邏輯是什麼? – 2012-01-29 14:41:08

+0

以圖像的左邊緣爲中心。然後使用等於其寬度一半的負邊距來完成對中 – mrtsherman 2012-01-29 14:58:57

1

給一個位置值,以便你想提供一個z-index的任何事情 - 在這種情況下,你.centeredImage。

+1

什麼kinakuta是說在儘可能少的話儘可能是已經固定的元素,絕對或相對定位是z-index的纔有效。由於centeredimage沒有這些z-index屬性什麼都不做。 – mrtsherman 2012-01-29 05:48:33

+0

謝謝你的迴應!在我上面發佈的代碼centerImage中居中頁面。問題在於overlayImage,因爲它出於某種原因固定在左側。我試圖添加位置:相對於居中圖像,它仍然居中,而overlayImage不是,如果我添加位置:絕對它也堅持左側overlayImage。我無法真正包裹這個。對我來說,合乎邏輯的事情是在containerPage div中定義區域,然後所有跟隨的元素都將該區域作爲參考...... – 2012-01-29 05:53:34

+0

它固定在左側,因爲它具有絕對定位。我將如何處理它是使您的相對定位的div的兩個圖像子元素。居中該div,然後給圖像絕對定位和適當的z-索引。 – kinakuta 2012-01-29 05:55:37