一、為什么要寫這篇文章
今天看到一個問題:
兩個div 都設置 display:inline-block,正常顯示;但是在第二個div中加一個塊級元素或者內聯元素,顯示就變了個樣,為什么?
<meta charset="utf-8"/><style>div{ width: 100px; height: 100px; border:1px solid red; display: inline-block;}.align{/* vertical-align: top;*/}</style><body> <div> </div> <div class="align">為什么?</div></body>
解決方案就是給第二個div加上:vertical-align:top。
關于vertical-align和基線我知道一點,但是這個問題我沒能答出,所以學習總結分享一下。
二、vertical-align干什么的?
w3c有一段相關信息如下:
'vertical-align'Value: baseline | sub | super | top | text-top | middle | bottom | text-bottom | <percentage> | <length> | inheritInitial: baselineApplies to: inline-level and 'table-cell' elementsInherited: noPercentages: refer to the 'line-height' of the element itselfMedia: visualComputed value: for <percentage> and <length> the absolute length, otherwise as specified
可以看到vertical-align影響inline-level元素和table-cell元素垂直方向上的布局。根據MDN描述,vertical-align對::first-letter和::first-line同樣適用。
適用于:
inline水平的元素
inline:<img>,<span>,<strong>,<em>,未知元素
inline-block:<input>(IE8+),<button><IE8+>....
'table-cell'元素
table-cell:<td>
所以默認情況下,圖片,按鈕,文字和單元格都可以用vertical-align屬性。
取值:
新聞熱點
疑難解答