输入后的断行没有html标记

时间:2010-10-06 21:00:00

标签: html css input label alignment

我正在尝试显示多个输入及其相应的标签。它们都是内联元素,我有一个工作解决方案,最后添加一个br标签,如此

<label for="hello"></label>
<input id="hello" type="text" />
<br>
<label for="stackoverflow"></label>
<input id="stackoverflow" />

我喜欢在没有多余HTML标记的情况下解决这个问题,即使用CSS。最简单的方法是什么?

我查看了与此类似的其他问题,但是按行而不是按列进行对齐。

2 个答案:

答案 0 :(得分:12)

您可以在输入周围包装标签并将其显示为块:

<style>
  label { display: block; }
</style>

<label>
  Hello: <input name="hello">
</label>
<label>
  StackOverflow: <input name="stackoverflow">
</label>

请注意,执行此操作时,您无需使用for="name"属性。

另一种方式(如果您不希望标签缠绕在您的输入上)是将标签浮动到左侧:

<style>
  label { float: left; clear: left; }
</style>

但是,我通常更喜欢标记,将labelinput连接到一个逻辑元素,称为字段

<div class="field">
  <label for="hello">Hello</label>
  <input name="hello">
</div>
<div class="field">
  <label for="stackoverflow">Stackoverflow</label>
  <input name="stackoverflow">
</div>

因为每个字段都是div,所以它会自动显示为一个块,但您也可以为各个字段控制它。

答案 1 :(得分:1)

尝试为display:inline-blockinput元素设置label。因此,您可以添加所有特定于块元素的css,例如witdhmargin-bottom

您还可以将inputlabel设置为display:block,并仅将margin-bottom添加到输入中。或者您可以将其反转并在标签上添加margin-top;)

如果要删除最后一个元素的边距,可以使用input:last-child {margin-bottom:0;}

input, label {display:block;}
input {margin-bottom:18px;}
input:last-child {margin-bottom:0;}

/* Or to be specific you can use the attribut-selector
   which only works on inputs with type="text"
*/
input[type="text"]:last-child {margin-bottom:0;}
相关问题