表單是使用者唯一真正會「操作」的部分,卻也是最容易被隨便對待的部分。同一份 HTML,在 Firefox 與 IE 裡往往長得不太一樣——高度差兩三像素、內距不同、和旁邊的文字對不齊。
把 input、select 與其他標籤(例如 a、label)混排時,常見三個毛病:
1px 0;IE 為 1px 0 3px 0。光是這三項加起來,就足以讓同一份表單在兩個瀏覽器裡相差好幾像素。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>表單對齊範例</title>
<style type="text/css">
body {
font-family: "宋體";
font-size: 12px;
}
table {
border-collapse: collapse;
border: solid red 1px;
}
td, th {
border: solid red 1px;
height: 40px;
}
label {
vertical-align: middle;
}
.inputtxt {
width: 200px;
padding: 0;
font-family: "宋體";
font-size: 12px;
height: 15px;
line-height: 15px;
vertical-align: middle;
border: solid #0000FF 1px;
}
</style>
</head>
<body>
<form action="#" method="post">
<table>
<tr>
<th width="44">first</th>
<td>
<input name="aj" type="text" maxlength="6" class="inputtxt" />
<label>知</label>
<input type="text" maxlength="6" class="inputtxt" />
</td>
</tr>
<tr>
<th>second</th>
<td><input name="bs" type="text" maxlength="6" class="inputtxt" /></td>
</tr>
</table>
</form>
</body>
</html>
input 在各瀏覽器中的兼容性對照
字型設定 | Firefox | IE 6.0 / 7.0
宋體 12px | 15px | 13px
宋體 14px | 17px | 15px
宋體 16px | 19px | 17px
關鍵有三處。padding: 0 抹平了兩瀏覽器不同的內距預設;height 與 line-height 設成同一個值,讓文字在框內垂直居中;vertical-align: middle 則讓 input 與身旁的 label 文字對齊中線,而不是各自依基線排列。
值得一提的是,對照表最後呈現的規律很一致:不論哪個瀏覽器,兩者高度差固定為 2px。這意味著只要用 height 明確指定,就不需要為每個瀏覽器分別寫 hack——差異是可預測的,可預測就能被統一處理。
今天不必再逐項手動對齊。引入 normalize.css 或套用 box-sizing: border-box,能省下絕大多數這類瑣事:
*, *::before, *::after { box-sizing: border-box }
加上這行之後,width: 200px 就是包含 border 與 padding 的總寬,IE 與現代瀏覽器的盒模型計算方式被拉齊,前面那些 2px 的差異也就不復存在。