对复选框和单选按钮进行分组的正确方法

Correct way to group checkboxes and radio buttons

我有一个单选按钮列表,我知道根据 W3C standards,所有 <form> 控件都应该有与之关联的标签。我是这样做的:

<label class="radio-inline">
    <input id="foo1" name="gender" value="M" type="radio"> Male
</label>
<label class="radio-inline">
    <input id="foo2" name="gender" value="F" type="radio"> Female
</label>

不过我还想有一个 'label' 告诉用户这两个单选按钮用于 gender 字段。我知道 <label> 在这里不是一个选项,因为一个 <label> 只与一个表单控件相关联。我四处搜索,发现使用 <fieldset><legend> 是可行的方法:

<fieldset class="form-group">
    <legend class="legend-label">Gender</legend>
    <label class="radio-inline">
        <input id="foo1" name="gender" value="M" type="radio"> Male
    </label>
    <label class="radio-inline">
        <input id="foo2" name="gender" value="F" type="radio"> Female
    </label>
</fieldset>

我使用 CSS 设置 legend.legend-label 的样式以使其像标签一样显示:

.legend-label {
    display: inline-block;
    width: inherit;
    padding: inherit;
    font-size: inherit;
    color: inherit;
    border: inherit;
    border-bottom: inherit;
    max-width: 100%;
    margin-bottom: 5px;
    font-weight: bold;
}

这是对单选按钮或复选框进行分组的正确方法吗?

就 HTML 而言,没有 "right way" 来对它们进行分组,您的两个示例都很好,您可以在任何其中为该组添加 header你喜欢的方式......但是,就语义,尤其是可访问性而言,嵌套在 <fieldset><legend> 中是正确的,并且是推荐的。

使用字段集和图例还提高了呈现页面时的可访问性non-visually(例如,通过屏幕阅读器,如果没有图例,上下文可能会丢失)。

关于这个问题,我遇到了很多困惑,因为许多开发人员似乎完全避免使用字段集,只依赖标签……公平地说,这在许多情况下就足够了。尽管如此,这仍然会导致新开发人员错误地质疑字段集的有效性。如 w3c.org 所述:

Authors sometimes avoid using the fieldset element because of the default display in the browser, which draws a border around the grouped controls. This visual grouping is also useful and authors should seriously consider retaining it (or some form of visual grouping). The visual effect can be modified in CSS by overriding the "border" property of the fieldset and the "position" property of the legend.

如果您输入的项目是相关的并且将它们分组有助于使信息更容易理解,那么一定要采取额外的步骤来调整您的 CSS 并使用字段集。 w3c.org 上的文章还指出:

Grouping controls is most important for related radio buttons and checkboxes. A set of radio buttons or checkboxes is related when they all submit values for a single named field.

因此,在您的性别选择单选输入示例中,字段集非常有意义。


有关何时以及何时不使用字段集的更多信息,请参阅 w3.org 中的示例。