2014-02-20 86 views
1

我需要在div的頂部和div的邊上居中放置一個圖像。換句話說,div的左邊緣和圖像的左邊緣之間的空間量必須與相反側的空間量相同。 div的上邊緣和圖像的上邊緣也是如此。我查看了this問題中的以下代碼並獲得了這個結果(除了類是ids外,幾乎完全相同)。垂直和水平對齊div中的圖像

CSS:

#img_holder { 
    background-color:#EC0610; 
    height: 500px; 
    float:left; 
    width: 550px; 
    text-align: center; 
} 

#vertical_center { 
    display: inline-block; 
    height: 100%; 
    vertical-align: middle; 
}  

#image { 
    vertical-align: middle; 
    max-height: 500px; 
    max-width: 550px; 
} 

HTML:

<div id="img_container"> 

    <div id="left_ctrl"> 

     Left control buttons 

    </div> 

    <div id="img_holder"> 

     <div id="vertical_center"> 

      <!-- Image inserted by javascript but the resulting html is this --> 
      <img id="image" src="../../images/bball1.jpg /> 

     </div> 

    </div> 

    <div id="right_ctrl"> 

     Right control buttons 

    </div> 

</div> 

我的形象出現水平居中,而不是垂直方向。任何想法爲什麼?瀏覽器是在Arch Linux上運行的Chromium 32。

+0

安置自己的HTML以及。 –

+0

對不起,它是。 – Hugo

回答

0

好,考慮this approach,你已經取得了你的標記錯誤。圖像不應嵌套在#vertical_center元素中。換言之,所述#image#vertical_center要素應該兄妹,如下所示:

<div id="img_holder"> 
    <div id="vertical_center"></div> 
    <img id="image" src="http://placehold.it/200" />   
</div> 

UPDATED DEMO

另外,就會有兩個inline-block元件之間的空白字符。你可以刪除,通過他們的父母的font-size設置爲0(或使用image replacement技術):

#img_holder { 
    font: 0/0 a; 
    /* other styles... */ 
} 
+0

哇如何愚蠢的我。謝謝,我完全錯過了。當我讀到解釋時,我也感到困惑,因爲我想知道爲什麼回答這個帖子的人是在討論把元素並排排列。 – Hugo

2

HTML:

<div id="img_holder"> 
    <img id="image" src="http://placehold.it/300x300"> 
</div> 

CSS:

#img_holder { 
    background-color:#EC0610; 
    height: 500px; 
    width: 550px; 
    position: relative; 
} 

#image { 
    position: absolute; 
    top: 50%; 
    left: 50%; 
    width: 300px; 
    height: 300px; 
    margin-top: -150px; /* Half the height */ 
    margin-left: -150px; /* Half the width */ 
} 

DEMO:JSFIDDLE