2011-12-26 108 views
2

我正在創建一個網站,需要兩個圖像重疊在一起,頂部圖像居中,但我也需要整個塊在頁面居中,所以我不要以爲我可以使用絕對定位,因爲我需要頁面可以縮放。疊加和居中兩張圖片,使用CSS

我使用 -

img.center { display: block; margin-left: auto; margin-right: auto; } 

在頁面上居中的圖像。

林不知道如果我已經解釋得很好,所以希望下面的模型將有所幫助。

enter image description here

enter image description here

我環顧四周成圖象重疊,但他們似乎都使用絕對定位,我似乎無法使其工作,使得圖像是使用該方法總是居中。

有沒有辦法做到這一點?如果一些示例代碼會非常有幫助,或者只是一個正確的方向。

謝謝。

回答

2
<div class="img_cont"> 
    <img src="1.png" alt="" class="first"/> 
    <img src="2.png" alt="" class="second"/> 
</div> 
<style type="text/css"> 
    div { 
     width: 300px; 
     height: 300px; 
     position: relative; 
      margin: 0 auto; 
    } 

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

    .second { 
     position: absolute; 
    } 
</style> 
<script type="text/javascript"> 
    $(".home_click").css("left", ($(".img_cont").width() - $(".second").width())/2 + "px"); 
    $(".home_click").css("top", ($(".img_cont").height() - $(".second").height())/2 + "px"); 
</script> 
2

您可以使用negative offset technique

<div class="img_cont"> 
    <img src="1.png" alt="" class="first"/> 
    <img src="2.png" alt="" class="second"/> 
</div> 
<style> 
.first, .second{ 
    margin:0 0 0 -200px; /* where 400px is width offset is/2) */ 
    position:absolute;top:0;left:50%; 
} 
.second{ 
    margin:0 0 0 -100px; /* let's guess second image was 200px wide */ 
} 
</style> 
0

<style type="text/css"> 
 
\t body { 
 
    margin: 0px; 
 
} 
 

 
.height-100vh { 
 
    height: 100vh; 
 
} 
 

 
.center-aligned { 
 
    display: box; 
 
    display: flex; 
 
    box-align: center; 
 
    align-items: center; 
 
    box-pack: center; 
 
    justify-content: center; 
 
} 
 

 
.background-image { 
 
    position: relative; 
 
} 
 

 
.text { 
 
    position: absolute; 
 
} 
 
</style>
<div class="height-100vh center-aligned"> 
 
    <img class="background-image" src="http://i.imgur.com/1aBfM.png" /> 
 
    <img src="http://i.imgur.com/DH3Qw.png" class="text"> 
 
</div>