是否有关于标签和输入HTML元素嵌套的最佳实践?

经典的方式:

<label for="myinput">My Text</label>
<input type="text" id="myinput" />

or

<label for="myinput">My Text
   <input type="text" id="myinput" />
</label>

当前回答

这两种方法都是正确的,但是将输入放在标签内会大大降低使用CSS进行样式化时的灵活性。

首先,<标签>限制了它可以包含的元素。例如,如果<input>不在<label>内,则只能在<input>和标签文本之间放置<div>。

其次,虽然有一些变通方法可以使样式更容易,比如用span包装内部标签文本,但有些样式将继承自父元素,这可能会使样式更复杂。

第三方编辑

根据我的理解,标签的html 5.2规范规定,标签内容模型是短语内容。这意味着只有内容模型为短语content <label>的标签才允许在</label>内。

内容模型必须包含的内容的规范描述 作为元素的子元素和子元素。 大多数被归类为措辞内容的元素只能 包含本身被归类为措辞内容的元素, 没有任何流内容。

其他回答

我更喜欢

<label>
  Firstname
  <input name="firstname" />
</label>

<label>
  Lastname
  <input name="lastname" />
</label>

over

<label for="firstname">Firstname</label>
<input name="firstname" id="firstname" />

<label for="lastname">Lastname</label>
<input name="lastname" id="lastname" />

主要是因为它使HTML更具可读性。实际上,我认为我的第一个例子更容易用CSS来设置样式,因为CSS可以很好地处理嵌套元素。

但我想这只是个人品味的问题。


如果需要更多样式选项,请添加span标记。

<label>
  <span>Firstname</span>
  <input name="firstname" />
</label>

<label>
  <span>Lastname</span>
  <input name="lastname" />
</label>

在我看来,代码看起来还是更好。

我通常会选择前两个。我曾见过使用第三个选项的场景,当无线电选项嵌入到标签和css包含类似的内容时

label input {
    vertical-align: bottom;
}

为了确保无线电的垂直对齐。

有关W3的建议,请参阅http://www.w3.org/TR/html401/interact/forms.html#h-17.9。

他们说这两种方法都可以。他们将这两个方法描述为显式(使用“for”和元素的id)和隐式(将元素嵌入到标签中):

明确:

for属性显式地将一个标签与另一个控件关联:for属性的值必须与相关联的控件元素的id属性的值相同。

隐式:

若要隐式地将一个标签与另一个控件关联,该控件元素必须位于label元素的内容中。在这种情况下,LABEL可能只包含一个控制元素。

就个人而言,我喜欢把标签放在外面,就像你的第二个例子一样。这就是FOR属性存在的原因。原因是我经常会在标签上应用样式,比如宽度,以使表单看起来更好(下面是简写):

<style>
label {
  width: 120px;
  margin-right: 10px;
}
</style>

<label for="myinput">My Text</label>
<input type="text" id="myinput" /><br />
<label for="myinput2">My Text2</label>
<input type="text" id="myinput2" />

这样我就可以避免表格和表单中的所有垃圾。

As most people have said, both ways work indeed, but I think only the first one should. Being semantically strict, the label does not "contain" the input. In my opinion, containment (parent/child) relationship in the markup structure should reflect containment in the visual output. i.e., an element surrounding another one in the markup should be drawn around that one in the browser. According to this, the label should be the input's sibling, not it's parent. So option number two is arbitrary and confusing. Everyone that has read the Zen of Python will probably agree (Flat is better than nested, Sparse is better than dense, There should be one-- and preferably only one --obvious way to do it...).

因为W3C和主要浏览器供应商的决定(允许“任何你喜欢的方式来做”,而不是“做正确的方式”),今天的网络是如此混乱,我们开发人员不得不处理如此复杂和多样化的遗留代码。