【问题标题】:Layout form fields without tables没有表格的布局表单域
【发布时间】:2011-11-24 12:41:06
【问题描述】:

我正在尝试实现一个非常简单的 HTML 布局。是这样的:

A Label:         [Input                ]
Another Label:   [Input                ]
The Last Label:  [Input                ]

在过去,我只是继续使用一张桌子来做这件事。否则,让输入控件正确排列会很痛苦。

谁能建议一种简单可靠的方法来实现这种布局而不使用表格?

谢谢。

【问题讨论】:

标签: html css forms


【解决方案1】:

您可以使用display: inline-block

<style type="text/css">
  label { display: inline-block; width: 200px; }
  ul { list-style: none; }
</style>

<ul>
  <li><label for="input1">A Label:</label> <input type="text" name="input1" id="input1"></li>
  <li><label for="input2">Another Label:</label> <input type="text" name="input2" id="input2"></li>
  <li><label for="input3">The Last Label:</label> <input type="text" name="input3" id="input3"></li>
</ul>

但是,为了使其垂直排列,您要么必须将标签输入对包装在另一个标签中(例如 &lt;li&gt;&lt;div&gt;),要么在输入后放置换行符。

【讨论】:

  • 不,你不需要为了让它们垂直排列而用额外的元素包装它们。特别是如果你给标签一个固定的宽度。
  • @DanMan 没错,我想我只是不喜欢花车
【解决方案2】:
<style>
  label { width: 200px; float:left; clear:left; } 
  input { float:left;} 
</style>
<form>
  <label for="fullname">Full Name:</label>
  <input type="text" name="fullname" id="fullname">
  <label for="email">Email Address:</label>
  <input type="text" name="email" id="email">
</form>

另外一个好处是,如果水平空间不足,输入将包裹在标签下方。

http://jsbin.com/anuziq(缩小浏览器窗口)

如果您实际上不希望它们环绕,我建议采用这种方法:

<style>
   label { white-space: nowrap; } 
   span { width: 200px; display: inline-block; }
</style>
<form>
  <label>
      <span>Full Name:</span>
      <input type="text" name="fullname">
  </label>
  <label>
      <span>Email Address:</span>
      <input type="text" name="email">
  </label>
</form>

根据我的经验,像这样构建 HTML 通常允许您可能想到的任何布局。希望输入始终低于标签?在 span 元素上使用 display:block。想要input 右侧的文字吗?只需在span 上使用float:right

这里的好处是您不需要forid 属性来连接标签和输入。只有当您不能将标签放在输入旁边时,它们才是真正需要的,例如在 2 个单独的表格单元格中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-14
    • 2019-10-04
    • 2018-01-25
    • 1970-01-01
    • 2018-03-26
    相关资源
    最近更新 更多