2010-11-08 40 views
0

鑑於這種HTML:如何讓我的圖像在div的中心?

<div> 
    <img id="image"> 
</div> 

如何獲得的圖像在div的中心去了?

目前它位於div的左上角。

我試圖

img#image 
{ 
    text-align:center; 
} 

但它並沒有區別。

回答

3

先給位置relative到DIV:

#div_id{ 
    position:relative; 
    width:400px; 
    height:200px; 
} 

這用於圖像的CSS:

#img_id{ 
    position:absolute; 
    top:100px; /* half of parent div's height */ 
    left:200px; /* half of parent div's width */ 
    display:block; 
} 
1
<img style='display:block; margin:0 auto' src='...'> 

將圍繞它的容器內的圖像

+0

各中心在橫軸上的圖像而不是垂直方向在div。當我應用這個時,圖像出現在div的頂部中心位置。 – pan 2010-11-08 18:58:10

0

CSS:

div { text-align: center; } 
#image { display: inline-block; vertical-align: middle; }