2011-08-09 27 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>對此更明確。