當某一列的儲存格內容高度不一,預設的靠上對齊會讓畫面顯得零碎。把整列的 vAlign 設為 top、middle 或 bottom,就能統一視覺基線。
<!DOCTYPE html>
<html>
<head>
<script>
function topAlign() {
document.getElementById('tr2').vAlign = "top";
}
</script>
</head>
<body>
<table width="50%" border="1">
<tr id="tr1">
<th>Firstname</th><th>Lastname</th><th>Text</th>
</tr>
<tr id="tr2">
<td>Peter</td><td>Griffin</td>
<td>Hello my name is Peter Griffin. I need a long text for this example.
I need a long text for this example.</td>
</tr>
</table>
<br>
<input type="button" onclick="topAlign()" value="Top-align table row" />
</body>
</html>vAlign 可以同時設在 table、tr、td/th 三個層級上,規則是「越靠近內容者優先」。也就是說:
· td 上設了 vAlign,就用 td 的
· td 沒設,就沿用所屬 tr 的
· tr 也沒設,才會看 table 的
這個層疊關係讓你可以「整列統一靠下,再個別把某格拉回靠上」,不必逐格設定。
跟單格對齊一樣,垂直對齊要有視覺效果,儲存格必須比內容高。範例中第三欄放了一段長文字,正是為了把列撐高、製造出剩餘空間,讓 top 與 middle 的差異看得出來。
vAlign 屬性已被 HTML5 棄用,建議改用 CSS:
var row = document.getElementById('tr2');
// 逐格套用(HTMLTableElement 沒有整列的 style)
Array.prototype.forEach.call(row.cells, function(cell) {
cell.style.verticalAlign = "top";
});更推薦的做法是定義 class 再由 JS 掛上:
/* CSS */
tr.top-align td { vertical-align: top; }
/* JS */
document.getElementById('tr2').classList.add('top-align');用 CSS 選擇器 tr.top-align td 一次涵蓋整列所有儲存格,程式碼比迴圈簡潔,樣式也更容易集中管理。
實務上,垂直對齊最常用在「一欄是長描述、其他欄是短欄位」的版面,例如商品清單、日誌列表。若你的表格走 RWD,在手機上轉為卡片式排版時,垂直對齊通常就不需要了——每張卡片各自獨立,改以 flex 排版控制內部間距會更合適。