表單要排得整齊,最省事的做法是讓 label 浮動並固定寬度,輸入欄位自然就被推到同一條垂直線上。這個範例示範了姓名、郵件、備註三個欄位加一顆送出鈕的排版。
<style type="text/css">
label {
float: left;
width: 80px;
}
form { margin: 0px }
input {
width: 180px;
border: 1px solid #808080;
}
textarea {
width: 250px;
height: 150px;
}
#sbutton {
margin-left: 80px;
margin-top: 5px;
width: 80px;
}
br { clear: left; }
</style>
<form action="" method="post"> <label for="user">姓名:</label> <input type="text" id="user" name="user" value="" /><br /> <label for="email">郵件:</label> <input type="text" id="email" name="email" value="" /><br /> <label for="comment">備註:</label> <textarea id="comment" name="comment"></textarea><br /> <input type="submit" id="sbutton" value="確定" /><br /> </form>
label 寬度 80px:這是所有欄位標籤的對齊基線。文字長度不一也沒關係,因為浮動後每個 label 都佔滿同樣寬度。
#sbutton 的 margin-left: 80px:送出鈕沒有 label 在前面,所以要手動推開 80px,讓它與輸入框的起始位置對齊。這個數字必須與 label 寬度一致,兩者是一組的。
br 的 clear: left:label 是浮動元素,若不清除浮動,下一組的 label 會黏在前一組右側。用 br { clear: left; } 一次處理掉所有換行點,比逐一加清除元素乾淨得多。
若表單需要置中,只要給 form 一個固定寬度加上 margin: 0 auto。若文字區域要與單行輸入框對齊右端而非左端,把 textarea 的寬度改成與 input 相同的 180px 即可。整個結構不依賴表格,欄位增減時只要複製一組 label + 控制項 + br 就好,維護成本遠低於 table 排版。