Labels, checkboxes and radio buttons

时光怂恿深爱的人放手 提交于 2019-12-01 06:03:58

The first part of Ssollinger's answer is correct:

The code should be:

<label for="firstName">First Name</label><input type="text" id="firstName" />
<label for="lastName">Last Name</label><input type="text" id="lastName" />
<fieldset>
  <legend>Gender</legend>
  <input type="radio" name="sex" id="sex-m" value="m">
  <label for="sex-m">Male</label>
  <input type="radio" name="sex" id="sex-f" value="f">
  <label for="sex-f">Female</label>
</fieldset>

When assistive technology hits the male radio button, most will read as: "Gender: male radio button 1 of 2 not selected."

Then you could use CSS on the fieldset, legend, the labels and inputs. If memory serves correctly fieldsets can be a bear to style, so i might end up adding a <div> to it:

<label for="firstName">First Name</label><input type="text" id="firstName" />
<label for="lastName">Last Name</label><input type="text" id="lastName" />
<fieldset>
  <legend>Gender</legend>
  <div>
  <input type="radio" name="sex" id="sex-m" value="m">
  <label for="sex-m">Male</label>
  <input type="radio" name="sex" id="sex-f" value="f">
  <label for="sex-f">Female</label>
  </div>
</fieldset>

Adding this <div> has no accessibility implications.

Like in the comment in ssollinger's answer, you could dump the fieldset and legend approach, but you would need to build everything to make it accessible, an example of a build out

ssollinger

I had thought about styling the <legend> tag to appear as though it's a label, and dispense with the label altogether for the radio button group, …

This is the correct way to do it. "Gender" is not a label for anything, the labels for the radio boxes are "male" and "female". "Gender" is the legend of the fieldset which groups the radio buttons together. The correct way to implement this form is to remove the "Gender" label and just leave the fieldset with legend "Gender".

Technically, you could probably add a <div> around the radio buttons and point the for= of the "Gender" label to that, but I'm quite sure that this will cause accessibility problems (haven't tried it with a screen reader though) so I would strongly recommend to get rid of the label for "Gender".

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!