資料表格加上「游標所在列高亮」與「奇偶列不同底色」,可讀性會明顯提升。以下用 :nth-child(odd) 與 :hover 兩個偽類就能完成,不需要 JavaScript。
注意 tbody 的寫法很關鍵:表頭 th 放在 tbody 之外,這樣奇偶計算才不會把標題列算進去。
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link href="table.css" type="text/css" rel="stylesheet" /> <title>table test</title> </head> <body> <table> <tr> <th>姓名</th> <th>性別</th> <th>班級</th> </tr> <tbody> <tr> <td>姓名</td> <td>男</td> <td>計算機科學與技術一班</td> </tr> <tr> <td>段萌</td> <td>男</td> <td>軟工一班</td> </tr> <tr> <td>段萌</td> <td>男</td> <td>軟工一班</td> </tr> <tr> <td>段萌</td> <td>男</td> <td>軟工一班</td> </tr> <tr> <td>段萌</td> <td>男</td> <td>軟工一班</td> </tr> </tbody> </table> </body> </html>
body{
margin:0 auto;
text-align:center
}
/* 設定 table 的 margin 為 auto 則表格居中顯示 */
table{
margin:0 auto;
border:0px;
solid:#000
}
/* 設定 th 表頭屬性,font-weight:bold 則顯示為粗體 */
table tr th{
height:28px;
width: auto;
line-height:28px;
background:#999;
font-weight:bold
}
table tbody tr{
height:28px;
line-height:28px;
text-align:center;
background:#FFF;
vertical-align:middle;
}
/* 用 :nth-child(odd) 取得奇數列並設定底色,
避免使用容易出錯的 expression */
table tbody tr:nth-child(odd){
background-color: #DEDEDE
}
/* 游標移入時整列變色 */
table tbody tr:hover{
background-color: #CCCCCC;
}
用 nth-child 取代 expression。早期為了在 IE 中做隔行變色,常見做法是寫 expression,效能差又容易出錯。:nth-child(odd) 是純 CSS 的原生方案,語意清楚且效能良好。若要支援更老的瀏覽器,備案是讓後端在輸出時就掛上 class="odd"。
hover 要寫在 nth-child 之後。兩者優先級相同時,後者覆蓋前者,因此 hover 必須放在最後,滑鼠移入才壓得住隔行底色。另外 :hover 套在 tr 上時,建議加上 tbody 限定範圍,避免表頭列也被高亮。