2013-02-03 140 views
6

的底部比方說,我有這樣的代碼:CSS:文本對齊頂部和細胞

<table> 
<tr> 
    <td> 
     <div id="top">top</div> 
     <div id="bot">bottom</div> 
    </td> 
</tr> 
</table> 

我試圖通過CSS對齊#top返回到細胞和#bot的頂部到底部。

#top { vertical-align:top; } 
#bot { vertical-align:bottom; } 

以上似乎並不奏效 - 它似乎沒有任何效果。這裏有一個代碼鏈接:http://jsfiddle.net/vKPG8/28/

任何解釋爲什麼會發生這種情況,以及如何解決它?

回答

4

vertical-align用於內聯元素,div是塊元素。試用position: absolutetop: 0bottom: 0

td { 
    position: relative; 
    width: 200px; 
    height: 100px; 
    border: solid 1px; 
} 

#top, #bot { position: absolute; } 
#top { top: 0; } 
#bot { bottom: 0; } 

演示:http://jsbin.com/iyosac/1/edit
在這裏獲得更多的信息:http://css-tricks.com/what-is-vertical-align/

+1

+1不錯清晰的解釋和工作演示。 – Menztrual

+0

不錯!感謝您的解釋和演示。它很棒! – dk123

+0

這不適用於Mozilla! –

7

使用位置接受的解決方案:絕對不是這個問題的一個跨瀏覽器兼容的解決方案,因爲Firefox不會(並根據到spec不應該)允許絕對定位在具有display:table-cell的表格單元格或元素中。

似乎沒有一個真正可靠的CSS解決這個問題的方法,但我確實有一個只適用於這種情況的CSS。基本上,我所做的是插入一個before元素,該元素的高度足以強制底部的文本行到底部,因爲它具有vertical-align:bottom set。這與放置頂部墊子基本相同,所以它不是什麼解決方案。

演示:http://jsfiddle.net/Be7BT/

td {width:200px;height:100px;border:solid 1px;} 
#top { 
    display: inline-block; 
    vertical-align:top; 
    width: 100%; 
} 
#bot { 
    display: inline-block; 
    vertical-align:bottom; 
    width: 100%; 
} 
#bot:before{ 
    content: ''; 
    display: inline-block; 
    height: 100px; 
} 
+1

有沒有辦法做到如果主td的高度最初不知道(例如,如果它的行跨度大於1,高度是由其他行決定的話) –

+0

不,我不這麼認爲,你可能需要設置高度javascrpit使這是一個動態的解決方案 – TorranceScott

+0

謝謝,它看起來好像沒有很好的跨瀏覽器的方式來實現這一點我已經嘗試了幾種方法 –

3

我有更好的想法,使用嵌套表:

<table width="100px" height="100px" border=1> 
    <tr> 
     <td valign="top">top</td> 
    </tr> 
    <tr height=100%> 
     <td valign="bottom">bottom 
     </td> 
    </tr> 
</table> 
+0

不幸的是,這也只適用於外部表格單元的高度是預設的。 –

1

做到這一點的方法是使用rowspan

<table><tr> 
    <td rowspan=2>tall<br>tall<br>tall<br>tall<br> 
    <td valign="top">top</td> 
</tr><tr> 
    <td valign="bottom">bottom</td> 
</tr></table>