【问题标题】:Break line after input without html markup没有html标记的输入后换行
【发布时间】:2011-04-22 01:37:51
【问题描述】:

我正在尝试显示一些输入及其相应的标签。它们都是内联元素,我有一个可行的解决方案,在末尾添加一个 br 标记,就像这样

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

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

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

【问题讨论】:

  • 只是为了论证,这 -- 是 -- 表格数据。有一个特定的 HTML 元素来处理它....只是说'

标签: html css input label alignment


【解决方案1】:

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

您还可以将inputlabel 设置为display:block,并将margin-bottom 仅添加到输入中。或者您可以反转它并在标签上添加一个边距顶部;)

如果要删除最后一个元素的边距,可以使用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;}

【讨论】:

  • 好建议,但它仍然会将所有内容放在一行(标签输入标签输入)而无需额外标记。
  • 你是对的。但在这种情况下,可以将两个元素都设置为 display:block 并仅向输入元素添加一个 margin-bottom 。我已经更新了我的答案。
【解决方案2】:

您可以将标签包裹在输入周围并将它们显示为块:

<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,它会自动显示为一个块,但您也可以对单个字段进行控制。

【讨论】:

  • 您的“字段” div 基本上也是我的做法。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-12-26
  • 1970-01-01
  • 2018-08-14
  • 1970-01-01
  • 1970-01-01
  • 2013-10-25
  • 2013-06-18
相关资源
最近更新 更多