2013-10-21 24 views
2

我有以下的HTML ....垂直圖像作爲對齊文本的

<div> 
    <img src="" /> 
    <span>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32. 
    </span> 
</div> 

而CSS ....

img{ 
    width: 50px; 
    height: 50px; 
    background-color: red; 
    display: inline-block; 
    float: left; 
    vertical-align: middle; /* not worked.... */ 
} 
span{ 
    overflow: hidden; 
    display: block; 
    padding-left: 10px; 
} 

demo

正如你所看到的在演示中,我想垂直對齊文本的紅色框。我也可以給例如400px的div的高度。

+0

你想要圖像與文本內聯? – Nitesh

+0

是的,圖像是內嵌文字.... –

回答

3

如果我要這樣做,我會使用一個表格顯示(它適用於all modern browsers)。

首先,更改您的標記來包裝你img在自己的span(這將作爲我們的表格單元格):

... 
<span> 
    <img /> 
</span> 
<span> 
    ... 
</span> 

然後應用以下樣式:

div { 
    display:table; 
} 

span { 
    display:table-cell; 
    vertical-align:middle; 
    padding-left:10px; 
} 

span:first-child { 
    padding-left:0; 
} 

img { 
    width:50px; 
    height:50px; 
    background:#f00; 
} 

JSFiddle demo

0

vertical-align物業只允許table元素或作爲他的答案, 提到詹姆斯Donelly至極顯示爲table-cell元素,但作爲替代,你可以使用:

margin-top: 50%;見例如: http://jsfiddle.net/KGg6H/19/

1

你可以也使用以下CSS使用紅色正方形圖案的絕對定位實現類似結果:

div { 
    border: 1px dotted blue; 
    position: relative; 
    min-height: 50px; 
} 
img{ 
    width: 50px; 
    height: 50px; 
    background-color: red; 
    display: block; 
    position: absolute; 
    left: 0; 
    top: 50%; 
    margin-top: -25px; 
} 
span{ 
    display: block; 
    margin-left: 60px; 
} 

在父容器上設置position: relative,然後使用絕對定位將img從頂部放置50%,然後應用margin-top: -25px將其垂直對齊父容器的高度。

您需要在span上設置文字margin-left: 60px以留出方形圖案的空間。

一個優點是設計不依賴於display: table-cell

一個缺點是,對於高度小於50px的文本塊,文本將對齊到正方形的頂部邊緣,根據設計要求這可能不合適。

見演示在:http://jsfiddle.net/audetwebdesign/796us/

腳註:我個人認爲display: table-cell是一個更強大的解決方案,只要瀏覽器支持。如果不支持table-cell,那麼設計將優雅地降低到與文本塊頂部邊緣對齊的圖案,這與絕對定位選項對短文本塊的限制相當。