2011-08-09 24 views
3

我正在尝试将表单布局从表格中移除并进入div和css的世界。用于对齐文本框和标签的CSS

虽然在我的布局中我很困难。我想订购标签直接位于输入上方的元素。 这是它目前的样子: Screenshot

我想区标签和文本框垂直对齐,但他们似乎正在形成楼梯模式。

这里的CSS:

#content 
{ 
    position: absolute; 
    top: 110px; 
    left: 350px; 
    width: 775px; 
    height: 605px; 

} 

#content label 
{ 
    display:inline; 
    margin-right:4px; 
    vertical-align:top; 
} 

#content input 
{ 
    float:left; 
    margin:1px 20px 1px 1px; 
} 

和HTML:

<div id="content"> 
     <label for="txt_RequestId">Request Id</label> 
     <input id="txt_RequestId" type="text" /> 

     <label for="txt_District">District</label> 
     <input id="txt_District" type="text" /> 
</div> 
+1

其实,我会建议使用表格表格。正如你现在所知,布局过程要容易得多。 –

+0

@Evan真的,好像我一直在阅读所有关于不使用表格的好处,除了表格数据。你为什么推荐桌子? – mint

+0

你可以将''标签换成'

回答

10

input元素嵌套在label中,以便对文本标签和字段进行分组。

这种用法在HTML4 spec规定:

To associate a label with another control implicitly, the control element must be within the contents of the LABEL element. In this case, the LABEL may only contain one control element. The label itself may be positioned before or after the associated control.

<div id="content"> 
    <label> 
     Request Id<br /> 
     <input id="txt_RequestId" type="text" /> 
    </label> 

    <label> 
     District<br /> 
     <input id="txt_District" type="text" /> 
    </label> 
</div> 

CSS:

#content 
{ 
    position: absolute; 
    top: 110px; 
    left: 350px; 
    width: 775px; 
    height: 605px; 
} 

#content label 
{ 
    display:inline; 
    float:left; 
    margin-right:4px; 
    vertical-align:top; 
} 

example

然后申请display:inlinefloat:left<label> s(或使用display:inline-block代替,如果您不必担心旧版浏览器example

+0

这很好,但有一个问题,使用
被认为是不好的做法;有没有更好的方法,或者这是普遍接受的方法。 CSS方法将是首选。 – mint

+1

true'
'可以说是不好的,你可以通过设置''字段为'display:block' [例子](http://jsfiddle.net/pxfunc/LHmEE/2/)来解决这个问题。 – MikeM

1

更改此

#content input 
{ 
    float:left; 
    margin:1px 20px 1px 1px; 
} 

这个

#content input 
{ 
    display:inline; 
    margin:1px 20px 1px 1px; 
} 

即删除float:left并替换为display:inline;

实施例:http://jsfiddle.net/jasongennaro/ptKEh/

EDIT

@mdmullinax指出问题还请文本高于输入字段

错过了;-)

在这种情况下,删除display规则并使用三个br s

<div id="content"> 
    <label for="txt_RequestId">Request Id</label><br /> 
     <input id="txt_RequestId" type="text" /> 

    <br /> 

    <label for="txt_District">District</label><br /> 
     <input id="txt_District" type="text" /> 
</div> 

订正例如:http://jsfiddle.net/jasongennaro/ptKEh/2/

+0

该问题还要求文本位于输入字段的上方 – MikeM

0

我一般用表对于被布局这样的形式。与CSS(IMO)相比,它们的工作要容易得多,而且结构更加清晰。

<table> 
    <tr> 
     <td> 
      <label for="txt_RequestId">Request Id</label> 
      <br /><input id="txt_RequestId" type="text" /> 
     </td> 
     <td> 
      <label for="txt_District">District</label> 
      <br /><input id="txt_District" type="text" /> 
     </td> 
    </tr> 
</table> 

CSS对于移动它们的容器周围的元素非常有用。但是,当你想要以一种非常规的方式定位事物时,依赖于其他元素,它可以真正混淆逻辑。 <table>对此更明确。