2012-02-26 125 views
1

我正在嘗試爲所有瀏覽器訪問。不同的瀏覽器給出了不同的結果(IE對我來說最成問題)。我包含了截圖,以便您可以看到我在說什麼。HTML表單對齊 - 輸入與標籤

這是形式的外觀在Safari,Firefox和Chrome:

enter image description here

http://imageshack.us/photo/my-images/210/bildschirmfoto20120226u.png/

這是形式的外觀在IE6和IE7:

enter image description here

http://imageshack.us/photo/my-images/37/bildschirmfoto20120226u.png/

這是IE8和IE9:

enter image description here

http://imageshack.us/photo/my-images/39/bildschirmfoto20120226u.png/

HTML

<form method="post" action="?test" id="form"> 
    <label for="user">USERNAME</label> 
    <input type="text" name="user" id="user" maxlength="100" title="Please enter your username." data-h5-errorid="empty-user" tabindex="1" required /> 
    <div id="empty-user" class="fail">This stuff will get replaced by the title contents.</div> 
    <label for="password" class="clear">PASSWORD</label> 
    <input type="password" name="password" id="password" maxlength="100" title="Please enter your password." data-h5-errorid="empty-password" tabindex="2" required /> 
    <div id="empty-password" class="fail">This stuff will get replaced by the title contents.</div> 
</form> 

CSS

label { 
    background: yellow; 
    font-size: 12px; 
    font-weight: bold; 
    width: 100px; 
    float: left; 
    margin-right: 50px; 
    text-align: right; 
    cursor: pointer; 
} 

input { 
    height: 30px; 
    background-color: #fafafa; 
    border: 1px solid #abaaaa; 
    width: 300px; 
    margin: 5px 0 5px 0; 
    float: right; 
} 

現在我的問題是,我如何對齊標籤,使它們與輸入字段垂直對齊?我在這裏使用了搜索,大部分時間都是這樣的:

vertical-align: middle; 

被推薦,但這根本不起作用。 Safari,Chrome和Firefox的唯一修正是爲標籤添加邊距頂部或頂部填充,但這會破壞IE8和IE9中的表單。

我該怎麼處理這個問題?降低輸入字段的高度對我來說不是一種選擇。

+0

我會*真*推薦**不**使用'元素'這樣的選擇器;使用像'form label.text'這樣的類選擇器,或者像'#form label'這樣的後代選擇器。只是它不適用於頁面上每種*類型的元素。 – 2012-02-26 00:23:49

+0

好的,謝謝,我會的! – Sven 2012-02-26 00:28:55

回答

4

在輸入標籤(某處)後放置一個clear:both

我建議你在你的表單中增加更多的標記用於額外的定製。通常我喜歡做這樣的表格:

<div class="field"> 
    <label for="user">USERNAME</label> 
    <div class="field-subject"> 
     <input type="text" name="user" id="user" maxlength="100" title="Please enter your username." data-h5-errorid="empty-user" tabindex="1" required /> 
    </div> 
</div> 

.field { 
    overflow: auto; /* this "clears" the floated elements */ 
    margin-bottom: 10px; 
} 

.field label { 
    float: left; 
    width: 200px; 
} 

.field .field-subject { 
    float: left; 
    width: 500px; 
} 
+0

這將'垂直對齊'標籤中的文字? – 2012-02-26 00:29:51

+0

我相信你可以嘗試...如果這不起作用,你可以將標籤設置爲'display:block'並添加一些邊距/填充。 – Matthew 2012-02-26 00:34:18