<label> 在带有收音机的表单中的语义用法

Semantic usage of the <label> in the form with radios

根据the HTML5 Doctor

The label represents a caption in a user interface. The caption can be associated with a specific form control, known as the label element's labeled control, either using for attribute, or by putting the form control inside the label element itself.

所以将其放入带有单选按钮的上下文中。在要求您在表单中选择最喜欢的水果的示例中,如果我说标签 "Apple" 是其单选按钮的 <label>,为了使标签可点击,我会将无线电控制里面,如:

<label>
   <input type="radio" name="fruit" value="apple"/> Apple
</label>

并且由于他们示例中的 <label> 元素也显示为整个输入值的标签,这表明我的问题 "Your favourite fruit?" 进入标签,从而使整个部分充满标签?

<label>Your favourite fruit?</label>
<label>
    <input type="radio" name="fruit" value="apple"/> Apple
</label>
<label>
    <input type="radio" name="fruit" value="banana"/> Banana
</label>
<label>
    <input type="radio" name="fruit" value="watermelon"/> Watermelon
</label>

对吗?

然后第一个 <label> 上的 for 属性在他们的示例中持有问题,指的是元素的 id。但是我不能这样做,因为我有 3 个元素,所以这意味着我不可能使用 for 属性?

解决这个问题的语义方法是用 fieldset 元素对单选按钮进行分组。

<fieldset>
    <legend>Your favourite fruit?</legend>
    <label>
        <input type="radio" name="fruit" value="apple"/> Apple
    </label>
    <label>
        <input type="radio" name="fruit" value="banana"/> Banana
    </label>
    <label>
        <input type="radio" name="fruit" value="watermelon"/> Watermelon
    </label>
</fieldset>

W3C 的辅助功能教程推荐您使用这种方案:https://www.w3.org/WAI/tutorials/forms/grouping/ and MDN's Fieldset Article: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/fieldset

可以使用 CSS 改进字段集的默认呈现。其中一个例子是这里 https://design-system.service.gov.uk/components/radios/