2014-03-02 52 views
1

http://jsfiddle.net/cECRj/中心形象Y和X

我怎麼會居中圖像,使其在DIV的完整的中心?

#box 
{ 
border: 1px solid; 
margin: 0px 10px 0px 0px; 
width: 250px; 
height: 200px; 
border-radius: 35px; 
-webkit-border-radius: 35px; 
-moz-border-radius: 35px; 
border: 1px solid #E8E8E8; 
display:inline-block; 
} 

<div id="box"> 
<img src="cleaning1.jpg" height="150px" width="200px"> 
</div> 
+0

爲了對準一個未知的尺寸的圖像垂直和水平中心,你可以參考[我的答案在這裏(http://stackoverflow.com/questions/18516317/vertically-align-an-image-inside-a- DIV-與響應高/ 18516474#18516474)。 –

+0

圖像大小會改變嗎? –

+0

@HashemQolami我累了,但我無法上班 – user3354493

回答

0

您可以將圖像的默認顯示類型更改爲inline-block,並在inline-block之外創建一個全高僞元素。

然後將內聯元素垂直對齊vertical-align: middle;,並使用text-align: center;爲父#box獲取圖像。

而且,會有你必須刪除它內聯(嵌段)元素之間的空白字符。你可以參考my answer來做到這一點。

在這裏你去:

#box { 
    /* Other styles here... */ 

    text-align: center; /* align the inline(-block) elements horizontally */ 
    font: 0/0 a;   /* remove the gap between inline(-block) elements */ 
} 

#box:after {   /* create a full-height inline block pseudo=element */ 
    content: ' '; 
    display: inline-block; 
    vertical-align: middle; /* vertical alignment of the inline element */ 
    height: 100%; 
} 

#box img { 
    display: inline-block; 
    vertical-align: middle; /* vertical alignment of the inline element */ 
} 

WORKING DEMO

進一步的細節可以參考my answer here

+0

謝謝。我沒有這樣做,這就是爲什麼它不起作用。 – user3354493

+0

哈希姆,會有一個原因,爲什麼我的txt沒有出現在盒子的div?我的計劃是將圖像居中,然後寫在上面。但是,如果我放入文本,則不會顯示任何文本。 – user3354493

+0

如果這就是您想要的內容,請使用我的解決方案,因爲文本會浮在頂部。這是一個更好的方式來解決你的問題,而不是添加不必要的元素和CSS代碼,這實際上並不需要在那裏。 – LGSon

0

由於哈希姆建議,或者如果只有在框中居中的圖像,這樣做:

演示:http://jsfiddle.net/J7xha/1/

HTML

<div id="box"> 
</div> 

CSS

#box { 
    background: transparent url("http://placehold.it/240x190") no-repeat center center; 
    border: 1px solid; 
    margin: 0px 10px 0px 0px; 
    width: 250px; 
    height: 200px; 
    border-radius: 35px; 
    -webkit-border-radius: 35px; 
    -moz-border-radius: 35px; 
    border: 1px solid #E8E8E8; 
    display:inline-block; 
} 
相關問題