表格加上邊框之後,預設的呈現樣式如下圖。可以注意到,標題預設是壓在表格上方的。
如果想把表格標題挪到下方,該怎麼做?在 CSS 中,我們用 caption-side 屬性來定義表格標題的位置。
語法:
caption-side:屬性值;
說明:
caption-side 屬性取值如下:
| caption-side 屬性值 | 說明 |
|---|---|
| top | 預設值,標題在頂部 |
| bottom | 標題在底部 |
舉例:
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>caption-side屬性</title>
<style type="text/css">
table,th,td{border:1px solid gray;}
caption{caption-side:bottom}
</style>
</head>
<body>
<table>
<caption>表格標題</caption>
<!--表頭-->
<thead>
<tr>
<th>表頭單元格1</th>
<th>表頭單元格2</th>
</tr>
</thead>
<!--表身-->
<tbody>
<tr>
<td>標準單元格1</td>
<td>標準單元格2</td>
</tr>
<tr>
<td>標準單元格1</td>
<td>標準單元格2</td>
</tr>
</tbody>
<!--表腳-->
<tfoot>
<tr>
<td>標準單元格1</td>
<td>標準單元格2</td>
</tr>
</tfoot>
</table>
</body>
</html>
在瀏覽器中預覽,效果如下:
分析:
表格標題就是 caption 元素。設定標題位置時,寫在 caption 元素或 table 元素上效果相同,但按慣例我們都寫在 caption 上——樣式放在它作用的對象身上,語意最清楚,也不容易造成混淆。