很多 CSS 愛好者對 HTML 表格避之不及,尤其在切表單的時候。明明已經是 XHTML + CSS 的年代,表單排版卻多半還在用 table 一格格拼。有沒有更貼近語意的做法,可以取代 table 鑲嵌的表單結構呢?
先說明立場:這不是要全面否定 table。表格在承載表格類資料時有其語意價值,該用的地方就該用。多數情況下我會用純 CSS 處理表單,但我也喜歡表格——重點是在正確的位置使用正確的元素,不必執著於「一定要 DIV + CSS」。如果需求本質上就是表格,直接寫 table 反而比用 display:table 去模擬更快更清楚。以下分享一種以純 CSS 取代表格來排版表單的做法。

新增一個 index.html,把下面的程式碼貼進 <body> 內。
<div id=”stylized” class=”myform”>
<form id=”form” name=”form” method=”post” action=”index.html”>
<h1>Sign-up form</h1>
<p>This is the basic look of my form without table</p><label>Name
<span class=”small”>Add your name</span>
</label>
<input type=”text” name=”name” id=”name” /><label>Email
<span class=”small”>Add a valid address</span>
</label>
<input type=”text” name=”email” id=”email” /><label>Password
<span class=”small”>Min. size 6 chars</span>
</label>
<input type=”text” name=”password” id=”password” /><button type=”submit”>Sign-up</button>
<div class=”spacer”></div></form>
</div>
光是讀這段標籤,你能想像它排版後的樣子嗎?下面是我對應的視覺結構示意:

每個 input 都配上一個 <label>,並用 <span> 包住簡短說明;label 與 input 都靠 CSS 的 float:left 排成左右兩欄。
把以下程式碼複製到頁面 <head> 中的樣式區塊(也可以另存為獨立 CSS 檔)。
body{
font-family:”Lucida Grande”, “Lucida Sans Unicode”, Verdana, Arial, Helvetica, sans-serif;
font-size:12px;
}p, h1, form, button{border:0; margin:0; padding:0;}
.spacer{clear:both; height:1px;}
/* ———– My Form ———– */
.myform{
margin:0 auto;
width:400px;
padding:14px;
}/* ———– stylized ———– */
#stylized{
border:solid 2px #b7ddf2;
background:#ebf4fb;
}#stylized h1 {
font-size:14px;
font-weight:bold;
margin-bottom:8px;
}#stylized p{
font-size:11px;
color:#666666;
margin-bottom:20px;
border-bottom:solid 1px #b7ddf2;
padding-bottom:10px;
}#stylized label{
display:block;
font-weight:bold;
text-align:right;
width:140px;
float:left;
}#stylized .small{
color:#666666;
display:block;
font-size:11px;
font-weight:normal;
text-align:right;
width:140px;
}#stylized input{
float:left;
font-size:12px;
padding:4px 2px;
border:solid 1px #aacfe4;
width:200px;
margin:2px 0 20px 10px;
}#stylized button{
clear:both;
margin-left:150px;
width:125px;
height:31px;
background:#666666 url(img/button.png) no-repeat;
text-align:center;
line-height:31px;
color:#FFFFFF;
font-size:11px;
font-weight:bold;
}
這只是表單排版的一種思路,你完全可以依自己的專案調性改寫配色、寬度與間距後重複使用。
實作時有兩個細節值得留意:一是 label 的 for 屬性別偷懶省略,它和 input 的 id 配對後,點擊文字即可聚焦輸入框,這是純 CSS 表單最容易忽略卻最影響可用性的地方;二是浮動排版記得清除,範例中用 .spacer 處理,實務上也可以改用 clearfix 偽元素,避免多一個空標籤。