是否有关于标签和输入HTML元素嵌套的最佳实践?
经典的方式:
<label for="myinput">My Text</label>
<input type="text" id="myinput" />
or
<label for="myinput">My Text
<input type="text" id="myinput" />
</label>
是否有关于标签和输入HTML元素嵌套的最佳实践?
经典的方式:
<label for="myinput">My Text</label>
<input type="text" id="myinput" />
or
<label for="myinput">My Text
<input type="text" id="myinput" />
</label>
当前回答
来自W3的HTML4规范:
标签本身可以放置在标签的前面、后面或周围 相关的控制。
<label for =“姓氏”>姓氏</label> <输入类型=“文本” id=“姓氏” />
or
<输入类型=“文本” id=“姓氏” /> <label for =“姓氏”>姓氏</label>
or
<标识> <input type="text" name="lastname" /> 姓 < / >标签
请注意,当表格用于布局时,标签在一个单元格中,其关联的表单字段在另一个单元格中,则不能使用第三种技术。
任何一个都是有效的。我喜欢使用第一个或第二个示例,因为它提供了更多的样式控制。
其他回答
参考WHATWG(编写表单的用户界面),将输入字段放在标签内并没有错。这样可以节省代码,因为不再需要标签中的for属性。
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和主要浏览器供应商的决定(允许“任何你喜欢的方式来做”,而不是“做正确的方式”),今天的网络是如此混乱,我们开发人员不得不处理如此复杂和多样化的遗留代码。
我非常喜欢将元素包装在<label>中,因为我不需要生成id。
我是一名Javascript开发人员,使用React或Angular生成可以被我或其他人重用的组件。然后很容易在页面中复制一个id,导致奇怪的行为。
一个值得注意的“gotcha”指示你永远不应该在<label>元素中包含一个以上的输入元素,它具有显式的“for”属性,例如:
<label for="child-input-1">
<input type="radio" id="child-input-1"/>
<span> Associate the following text with the selected radio button: </span>
<input type="text" id="child-input-2"/>
</label>
虽然对于表单特性来说,自定义文本值是单选按钮或复选框的次要属性,但label元素的点击聚焦功能会立即将焦点转移到id在其'for'属性中显式定义的元素上,这使得用户几乎不可能单击包含的文本字段来输入值。
就我个人而言,我尽量避免使用带有输入子元素的标签。从语义上讲,标签元素包含标签本身以外的内容似乎不合适。如果在标签中嵌套输入是为了达到某种美学效果,那么应该使用CSS。
就个人而言,我喜欢把标签放在外面,就像你的第二个例子一样。这就是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" />
这样我就可以避免表格和表单中的所有垃圾。