萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML 腳本教學

HTML fieldset 與 legend 標籤:表單分組語意化與樣式化指南

<fieldset> 為表單控件提供語意分組,配合 <legend> 標示群組標題,瀏覽器預設渲染圓角邊框 (IE) 或方框 (Firefox),支援 CSS 深度客製化。

標準結構

<fieldset>
  <legend>用戶登入</legend>
  <form action="/login" method="post">
    <label for="username">帳號:</label>
    <input type="text" id="username" name="username" required><br><br>
    <label for="password">密碼:</label>
    <input type="password" id="password" name="password" required><br><br>
    <input type="submit" value="登入">
    <input type="reset" value="重填">
  </form>
</fieldset>

核心特性

  • 區塊元素:獨佔一行,支援寬高、margin、padding
  • 必須成對閉合:`
    ...
    `
  • legend 置於首位:語意上為群組標題,瀏覽器渲染於邊框上方
  • 巢狀支援:fieldset 可巢狀,形成多層級分組
  • disabled 屬性:`
    ` 一次禁用群組內所有控件 (HTML5)

跨瀏覽器樣式統一

fieldset {
  border: 1px solid #ccc;
  border-radius: 8px;           /* 統一圓角 */
  padding: 1.5rem;
  margin: 1rem 0;
  min-width: 0;                 /* 防止內容撐大溢出 */
}
legend {
  font-weight: 600;
  font-size: 1.1rem;
  padding: 0 0.5rem;
  color: #333;
  width: auto;                  /* 修正 Firefox 全寬問題 */
}

無障礙增強

  • 螢幕閱讀器會宣告 `` 文字作為群組標籤
  • 配合 `
  • 鍵盤導航:Tab 進入 fieldset,方向鍵在群組內循環

實務應用場景

  1. 登入/註冊/設定表單的邏輯分區
  2. 問卷調查:每區塊一個 fieldset
  3. 複雜搜尋:基本/進階條件分組
  4. 多步驟精靈:每步一個 fieldset,JS 切換顯示
copyright © 萬盛學電腦網 all rights reserved