[英]Horizontally align text with a DIV
關於Stackoverflow有一些問題,這些問題詢問如何使用CSS(divs)水平對齊元素。 通常,這是使用float或display: inline-block
。
但是,我有一個非常簡單的要求,使用這些技術中的任何一種都很難使其完美工作。 我只想將一行文本與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使用..(請不要殺死我)一個<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上呈現如下:
好的,首先,方法1( inline-block
)的問題在於文本與DIV元素沒有垂直對齊(居中),看起來很尷尬。 而是,DIV的底部邊框與文本的底部對齊。 我嘗試調整填充和邊距來解決此問題,但這沒有幫助。
方法2( float
)看起來不錯,但是方法2的問題是如果文本更改為更長的時間會發生什么? 好...
因此,使用浮點數的問題是,如果文本變長,則DIV元素將被擊倒至下一行。 因此,這是不可接受的。 請注意,方法1( inline-block
)不存在此問題。
滿足所有要求的唯一方法是使用<table>
,但是我不想使用它,因為...好吧, 原因 。
那么,什么是最好的解決方案。 如何只將DIV與CSS一起使用,以得到與使用<table>
方法3相同的結果?
增加line-height:1em; vertical-align:top;
line-height:1em; vertical-align:top;
包含方法1的div文本似乎可以解決此問題(其中line-height是帶邊框的div的高度)。
我本人更喜歡inline-block
來float
因為在早期版本的IE中float
的不可預測性。 真的很難防止float
溢出到下一行,因為這是它的初衷!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.