开发者

Layout form fields without tables

I have a very simple HTML layout I'm trying to implement. It is something like this:

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

In the past, I'd just go ahead and use a table for this. Otherwise, it's a pain getting the input controls to line up correctly.

Can anyone suggest开发者_运维知识库 a simple and reliable way to implement this layout without using a table?

Thanks.


You can use 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>

However, in order for this to line up vertically, you either have to wrap the label-input pairs in another tag (such as <li> or <div>) or put linebreaks after the inputs.


<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>

With the added benefit that, if the horizontal space isn't sufficient, the inputs will wrap below the labels.

http://jsbin.com/anuziq (narrow down your browser window)

If you don't actually want them to wrap around, I suggest this approach:

<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>

From my experience, structuring the HTML like that usually allows for any layout you can possibly think of. Want the inputs always below the label? Use display:block on the span elements. Want the text to the right of the input? Just use float:right on the span.

Bonus here is that you don't need the for and id attributes to connect the label with the input. They're only really necessary, if you can't put the label right next to the input, like in 2 separate table cells.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜