HTML <th> 標簽

定義和用法

<th> 標簽定義 HTML 表格中的標題單元格。

HTML 表格有兩種單元格:

  • 標題單元格 - 包含標題信息(使用 <th> 元素創建)
  • 數據單元格 - 包含數據(使用 <td> 元素創建)

默認情況下,<th> 元素中的文本是粗體且居中的。

默認情況下,<td> 元素中的文本是普通的并且左對齊的。

另請參閱:

HTML 教程:HTML 表格

HTML DOM 參考手冊:TableHeader 對象

CSS 教程:設置表單的樣式

實例

例子 1

一個包含三行、兩個標題單元格和四個數據單元格的簡單 HTML 表格:

<table>
  <tr>
    <th>月份</th>
    <th>儲蓄</th>
  </tr>
  <tr>
    <td>一月</td>
    <td>¥3400</td>
  </tr>
  <tr>
    <td>二月</td>
    <td>¥4500</td>
  </tr>
</table>

親自試一試

例子 2

如何對齊 <th> 中的內容(使用 CSS):

<table style="width:100%">
  <tr>
    <th style="text-align:left">月份</th>
    <th style="text-align:left">儲蓄</th>
  </tr>
  <tr>
    <td>一月</td>
    <td>¥3400</td>
  </tr>
  <tr>
    <td>二月</td>
    <td>¥4500</td>
  </tr>
</table>

親自試一試

例子 3

如何將背景顏色添加到表格標題單元格(使用 CSS):

<table>
  <tr>
    <th style="background-color:#FF0000">月份</th>
    <th style="background-color:#00FF00">儲蓄</th>
  </tr>
  <tr>
    <td>一月</td>
    <td>¥3400</td>
  </tr>
 </table>

親自試一試

例子 4

如何設置表格標題單元格的高度(使用 CSS):

<table>
  <tr>
    <th style="height:100px">月份</th>
    <th style="height:100px">儲蓄</th>
  </tr>
  <tr>
    <td>一月</td>
    <td>¥3400</td>
  </tr>
</table>

親自試一試

例子 5

如何在表格標題單元格中規定不換行(使用 CSS):

<table>
  <tr>
    <th>月份</th>
    <th style="white-space:nowrap">為新車存的錢</th>
  </tr>
  <tr>
    <td>一月</td>
    <td>¥3400</td>
  </tr>
</table>

親自試一試

例子 6

如何垂直對齊 <th> 中的內容(使用 CSS):

<table style="width:50%;">
  <tr style="height:100px">
    <th style="vertical-align:bottom">月份</th>
    <th style="vertical-align:bottom">儲蓄</th>
  </tr>
  <tr>
    <td>一月</td>
    <td>¥3400</td>
  </tr>
</table>

親自試一試

例子 7

如何設置表格標題單元格的寬度(使用 CSS):

<table style="width:100%">
  <tr>
    <th style="width:70%">月份</th>
    <th style="width:30%">儲蓄</th>
  </tr>
  <tr>
    <td>一月</td>
    <td>¥3400</td>
  </tr>
</table>

親自試一試

例子 8

如何創建表格標題:

<table>
  <tr>
    <th>姓名</th>
    <th>電郵</th>
    <th>電話</th>
  </tr>
  <tr>
    <td>Bill Gates</td>
    <td>bill.gates@example.com</td>
    <td>138-1234-5678</td>
  </tr>
</table>

親自試一試

例子 9

如何創建帶有標題的表格:

<table>
  <caption>每月儲蓄</caption>
  <tr>
    <th>月份</th>
    <th>儲蓄</th>
  </tr>
  <tr>
    <td>一月</td>
    <td>¥3400</td>
  </tr>
  <tr>
    <td>二月</td>
    <td>¥4500</td>
  </tr>
</table>

親自試一試

例子 10

如何定義跨越多行或多列的表格單元格:

<table>
  <tr>
    <th>姓名</th>
    <th>電郵</th>
    <th colspan="2">電話</th>
  </tr>
  <tr>
    <td>Bill Gates</td>
    <td>bill.gates@example.com</td>
    <td>138-1234-5678</td>
    <td>186-2345-6789</td>
  </tr>
</table>

親自試一試

屬性

屬性 描述
abbr 文本 規定標題單元格中內容的縮寫版本。
colspan 數字 規定標題單元格應跨越的列數。
headers header_id 規定一個或多個與單元格相關的標題單元格。
rowspan 數字 規定標題單元格應跨越的行數。
scope
  • col
  • colgroup
  • row
  • rowgroup
表頭單元格是列頭、行頭還是一組列或行的頭部。

全局屬性

<th> 標簽還支持 HTML 中的全局屬性

事件屬性

<th> 標簽還支持 HTML 中的事件屬性

默認的 CSS 設置

大多數瀏覽器將使用以下默認值顯示 <th> 元素:

th {
  display: table-cell;
  vertical-align: inherit;
  font-weight: bold;
  text-align: center;
}

瀏覽器支持

Chrome Edge Firefox Safari Opera
Chrome Edge Firefox Safari Opera
支持 支持 支持 支持 支持