2014-02-20 84 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