<caption>:表格標題元素

Baseline 廣泛可用 *

此特性已相當成熟,可在許多裝置和瀏覽器版本上使用。自 ⁨2015 年 7 月⁩以來,各瀏覽器均已提供此特性。

* 此特性的某些部分可能存在不同級別的支援。

<caption> HTML 元素指定表格的標題(或名稱),為表格提供一個 可訪問名稱可訪問描述

試一試

<table>
  <caption>
    He-Man and Skeletor facts
  </caption>
  <tr>
    <td></td>
    <th scope="col" class="heman">He-Man</th>
    <th scope="col" class="skeletor">Skeletor</th>
  </tr>
  <tr>
    <th scope="row">Role</th>
    <td>Hero</td>
    <td>Villain</td>
  </tr>
  <tr>
    <th scope="row">Weapon</th>
    <td>Power Sword</td>
    <td>Havoc Staff</td>
  </tr>
  <tr>
    <th scope="row">Dark secret</th>
    <td>Expert florist</td>
    <td>Cries at romcoms</td>
  </tr>
</table>
caption {
  caption-side: bottom;
  padding: 10px;
  font-weight: bold;
}

table {
  border-collapse: collapse;
  border: 2px solid rgb(140 140 140);
  font-family: sans-serif;
  font-size: 0.8rem;
  letter-spacing: 1px;
}

th,
td {
  border: 1px solid rgb(160 160 160);
  padding: 8px 10px;
}

th {
  background-color: rgb(230 230 230);
}

td {
  text-align: center;
}

tr:nth-child(even) td {
  background-color: rgb(250 250 250);
}

tr:nth-child(odd) td {
  background-color: rgb(240 240 240);
}

.heman {
  font:
    1.4rem "molot",
    sans-serif;
  text-shadow:
    1px 1px 1px white,
    2px 2px 1px black;
}

.skeletor {
  font:
    1.7rem "rapscallion",
    fantasy;
  letter-spacing: 3px;
  text-shadow:
    1px 1px 0 white,
    0 0 9px black;
}

屬性

此元素包含全域性屬性

已棄用屬性

以下屬性已棄用,不應使用。它們僅在更新現有程式碼時作為參考和出於歷史興趣而在此處記錄。

align 已棄用

指定標題應顯示在表格的哪一側。可能的 列舉 值是 lefttoprightbottom。請使用 caption-sidetext-align CSS 屬性,因為此屬性已棄用。

用法說明

  • 如果包含 <caption> 元素,它必須是其父級 <table> 元素的第一個子元素。
  • <table> 巢狀在 <figure> 中,並且是 figure 的唯一內容時,應透過 <figure><figcaption> 來為其新增標題,而不是在 <table> 中巢狀 <caption>
  • 應用於表格的任何 background-color 都不會應用於其標題。如果您希望表格和標題具有相同的背景色,也請為 <caption> 元素新增 background-color

示例

請參閱 <table> 以獲取一個完整的表格示例,其中介紹了常見的標準和最佳實踐。

帶標題的表格

此示例演示了一個包含標題以描述所呈現資料的基本表格。

這樣的“標題”對於快速瀏覽頁面的使用者很有幫助,並且對視障使用者尤其有利,它允許他們在不要求螢幕閱讀器朗讀大量單元格內容的情況下,快速確定表格的相關性,從而瞭解表格的內容。

HTML

<caption> 元素用作 <table> 的第一個子元素,其文字內容類似於標題,用於描述表格資料。在 <caption> 之後,使用 <tr><th><td> 元素建立了三行,第一行為標題行,共有兩列。

html
<table>
  <caption>
    User login email addresses
  </caption>
  <tr>
    <th>Login</th>
    <th>Email</th>
  </tr>
  <tr>
    <td>user1</td>
    <td>user1@example.com</td>
  </tr>
  <tr>
    <td>user2</td>
    <td>user2@example.com</td>
  </tr>
</table>

CSS

使用一些基本 CSS 來對 <caption> 進行對齊和高亮顯示。

css
caption {
  caption-side: top;
  text-align: left;
  padding-bottom: 10px;
  font-weight: bold;
}

結果

技術摘要

內容類別 無。
允許內容 流內容.
標籤省略 如果元素後面緊跟著的不是 ASCII 空白符或註釋,則可以省略結束標籤。
允許父級 作為其第一個後代元素的 <table> 元素。
隱式 ARIA 角色 caption
允許的 ARIA 角色 不允許 role
DOM 介面 HTMLTableCaptionElement

規範

規範
HTML
# the-caption-element

瀏覽器相容性

另見