2012-07-15 118 views
1

在Stackoverflow上有幾個問題需要關於使用CSS(div)水平對齊元素。一般來說,這是通過使用浮動塊或display: inline-block完成的。將文本與DIV水平對齊

但是,我有一個非常簡單的要求,並且我很難使用這些技術中的任何一種來使其完美工作。我只是想將一行文本與DIV元素水平對齊。

所以,基本上,有3種方式這樣做的:

方法1(使用display: inline-block

<div style = "display: inline-block;">Foo</div> 
<div style = "display: inline-block; padding-left: 19px"> 
    <div style = "border: 1px solid #000000; height: 1em; width: 100px"></div> 
</div> 

方法2(使用float

<div style = "width: 150px"> 
    <div style = "float:left">Foo</div> 
    <div style = "float:right"> 
     <div style = "border: 1px solid #000000; height: 1em; width: 100px"></div> 
    </div> 
</div> 

方法3 方法3使用。(請不要殺我)一個<table>

<table style = "width: 150px" cellpadding = "0" cellspacing = "0" border = "0"> 
    <tr> 
     <td style = "width: 40px"> 
      Foo 
     </td> 
     <td> 
      <div style = "border: 1px solid #000000; height: 1em; width: 100px"></div> 
     </td> 
    </tr> 
</table> 

這三種方式呈現這樣的Firefox:

enter image description here

好吧,首先,用方法1(問題inline-block)是文本不與DIV元素垂直對齊(居中),看起來很尷尬。相反,DIV的底部邊框與文本底部對齊。我試着調整填充和邊距來解決這個問題,但它沒有幫助。

方法2(float s)看起來不錯,但方法2的問題是如果文本更改爲更長的內容會發生什麼?嗯......

enter image description here

所以使用花車的問題是,如果文本變長,DIV元素被撞倒到下一行。所以這是不可接受的。請注意方法1(inline-block)沒有此問題。

滿足所有要求的唯一方法是使用<table>的方法,但我不想使用它,因爲...好吧,reasons


那麼,這裏最好的解決方案是什麼。我如何才能使用CSS的DIV獲得與方法3相同的結果,該方法使用<table>

+0

沒有跨度,縮進,邊距,也沒有javascript? – 2012-07-15 21:20:02

回答

1

line-height:1em; vertical-align:top;添加到包含方法1的div的文本似乎解決了此問題(其中line-height是邊框div的高度)。

由於IE早期版本中float的不可預測性,我自己更喜歡inline-blockfloat。這也是很難阻止float溢出到下一行,因爲這是它的設計,真的!