CSS3 Zebra striping table

  • 1343
  • 0

CSS3 提供針對表格

裡子集合(某一行、某一列) 設定樣式,關鍵字 nth-child

CSS3 提供針對表格 <table> 裡子集合(某一行、某一列) 設定樣式,關鍵字 nth-child

語法如:

th:nth-child(2n+1) { . . . }

th / tr / td 均可

小括弧 中間運算式 2n 表示除以 2,+1 表示 餘 1,(2n+1) 表示符合除以2餘1的範圍

舉例,這是一個簡單尚未做任何設定的 HTML Table

image

透過

/*1 - 設定所有標題的樣式*/
th:nth-child(1n) {
	width:60px;
    text-align:center;
    background-color: silver;
}
/*2 - 設定第一欄的樣式*/
td:nth-child(1){
	text-align:center;
	background-color: silver;
}
/*3 - 設定複數列的樣式*/
tr:nth-child(2n){
		background-color: lightblue;
}
/*4 - 設定單數列的樣式*/
tr:nth-child(2n+1){
		background-color: lightgreen;
}
/*5- 設定第六欄的樣式*/
td:nth-child(6n){
		text-align:center;
		background-color: gold;
}

image

使用 Zebra striping tables ,讓 Html 的表格更乾淨,大幅減少行內樣式。

參考來源: Zebra striping tables with CSS3

完整範例: https://gist.github.com/robinli/8002537