← HTML / CSS Course

WEB FOUNDATION · 46

Semantic HTML / Accessibility:同樣長相,不代表同樣角色

一堆 div 也能被 CSS 排得很漂亮,但 Browser、keyboard、screen reader 與未來維護者需要的是內容角色。Semantic HTML 讓結構本身就帶意義。

Learning outcomes

1. Landmark / content structure

<header>...</header>
<nav aria-label="Primary">...</nav>
<main>
  <article>...</article>
</main>
<footer>...</footer>

元素先回答「這段是什麼」,CSS 再回答「怎麼看」。

2. Button vs Link

Button

執行 action:Save、Open dialog、Toggle。

Anchor

導航到 URL / resource。

<button type="button">Save</button>
<a href="/courses">Courses</a>

3. Table 表達真正二維資料

<table>
  <thead>
    <tr>
      <th scope="col">Course</th>
      <th scope="col">Level</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>JavaScript</td>
      <td>Beginner</td>
    </tr>
  </tbody>
</table>

Table 不應拿來當整頁 layout system。

4. Media 與替代內容

<video controls>
  <source
    src="intro.mp4"
    type="video/mp4"
  >
  <track
    kind="captions"
    src="intro-zh.vtt"
    srclang="zh-Hant"
  >
</video>

影音可及性不只 controls;caption/transcript 也要依內容需要規劃。

5. Native semantics 優先

能用 button 就不要從 div + click + tabindex + keyboard handler 重造一個不完整 button。Native controls 已提供大量 interaction/accessibility behavior。

Project checkpoint:Course Profile v3

<header>
  <h1>JavaScript Course</h1>
</header>

<nav>...</nav>

<main>
  <article>
    <h2>Overview</h2>
    ...
  </article>

  <section>
    <h2>Modules</h2>
    <table>...</table>
  </section>
</main>

Debug evidence:滑鼠能用、鍵盤不能用

先檢查 element role、focusability、keyboard semantics,再看 event handler。若用原生 button,很多行為一開始就已正確。

Knowledge check

  1. button 和 anchor 的核心語意差在哪?
  2. table 適合 layout 嗎?
  3. 為什麼 semantic element 可能畫面幾乎不變卻仍值得改?
  4. 把 v2 的 div 結構改成 v3 semantic document。