CSS3 提供 :nth-child() 與 :nth-of-type() 偽類,無需 JavaScript 即可實現列表、表格的斑馬紋效果。
#list1 li:nth-of-type(odd) { background:#00ccff; } /* 奇數行 */
#list1 li:nth-of-type(even) { background:#ffcc00; } /* 偶數行 */
:nth-child(An+B) 中,A 為週期長度,B 為起始偏移(1-based)。
/* 每 4 行一組,第 1 行藍 */
#list2 li:nth-child(4n+1) { background:#00ccff; }
/* 同一組內第 2、3、4 行不同色 */
#list00000 li:nth-child(4n+2) { background:#090; }
#list00000 li:nth-child(4n+3) { background:#009; }
#list00000 li:nth-child(4n+4) { background:#990; }
| 選擇器 | 計算基準 |
|---|---|
:nth-child(n) | 父元素下所有子元素順序(含不同標籤) |
:nth-of-type(n) | 父元素下同類型標籤順序(忽略其他標籤) |
建議列表結構單純時用 nth-child,混雜標籤時用 nth-of-type。
tbody tr:nth-child(odd) { background:#f9f9f9; }
tbody tr:nth-child(even) { background:#fff; }