首页 / HTML5 入门教程 / label 与表单可访问性

HTML5 入门教程

label 与表单可访问性

本教程共 110 篇 · 第 62 篇 · 更新于 2026-07-28 · 约 4 分钟阅读

HTML5HTML5 入门教程表单label可访问性forid屏幕阅读器

62. label 与表单可访问性

本节目标:理解 label 的重要性,学会正确关联标签和输入控件。

每个输入框都应该有 label。这不是建议,是基本要求。

label 解决了什么问题

  1. 屏幕阅读器:点进输入框时,读出标签内容,用户知道该填什么
  2. 点击区域:点击标签等于点击输入框,小按钮变大靶子
  3. 语义关联:告诉浏览器这两个元素是一家人

显式关联:for + id

最推荐的方式,用 for 属性绑定输入控件的 id

<label for="email">邮箱:</label>
<input type="email" id="email" name="email">

点击”邮箱:“文字,光标自动跳进输入框。

隐式关联:嵌套

把 input 直接放在 label 里面。

<label>
  邮箱:
  <input type="email" name="email">
</label>

效果一样,但 HTML 结构稍显拥挤。

显式关联更灵活。比如 label 和 input 可以放在不同位置(表格布局时很有用)。

与 checkbox/radio 搭配

label 在小控件上的价值最大。

<input type="checkbox" id="agree" name="agree" value="yes">
<label for="agree">我已阅读并同意服务条款</label>

点击”我已阅读并同意服务条款”就能勾选,不用瞄准那个小方框。

没有 label 的话,用户只能点那个 16x16 的小方块。手机上简直是噩梦。

与 select 搭配

<label for="country">国家:</label>
<select id="country" name="country">
  <option value="cn">中国</option>
  <option value="us">美国</option>
</select>

placeholder 不等于 label

<!-- 不好:只有 placeholder -->
<input type="text" placeholder="请输入用户名">

<!-- 好:label + placeholder -->
<label for="user">用户名:</label>
<input type="text" id="user" placeholder="例如:zhangsan">

placeholder 是示例提示,不是标签。输入开始后它就消失了。

屏幕阅读器可能跳过 placeholder。所以绝不能用它替代 label。

完整示例

一个规范的可访问登录表单:

<form action="/login" method="post">
  <p>
    <label for="username">用户名:</label><br>
    <input type="text" id="username" name="username"
           required autocomplete="username">
  </p>
  <p>
    <label for="password">密码:</label><br>
    <input type="password" id="password" name="password"
           required autocomplete="current-password">
  </p>
  <p>
    <input type="checkbox" id="remember" name="remember">
    <label for="remember">记住我</label>
  </p>
  <p>
    <button type="submit">登录</button>
  </p>
</form>

每个输入框都有 label。每个 label 都正确关联。这就是专业表单该有的样子。

Note

属性告诉浏览器这个字段的含义,让浏览器能正确填充保存的登录信息。