border-collapse
table { border-collapse: collapse; } table, th, td { border: 1px solid black; }
nth-child
nth-child(an+b)
even 偶數行
tr:nth-child(even){ background-color:#000000; }
odd 單數行
tr:nth-child(odd){ background-color:#000000; }
(n) An+B 指定元素
An + B自定義數字:
A=元素數
B=至第n個元素
n=從0開始
範例說明
nth-child(2n+1) = nth-child(odd)
nth-child(2n) = nth-child(even)
nth-child(7) = 表示第7元素
nth-child(5n) = 表示第5元素,5[= 5×1],10 [= 5×2],15 [= 5×3]…
nth-child(n+7) = 表示第7元素及以下所有元素,7 [=0+7], 8 [=1+7], 9 [=2+7]…
nth-child(-n+3) = 表示前3個元素 [=-0+3, -1+3, -2+3]…
nth-child(3n+4) = 表示第4元素 [=(3×0)+4], 7 [=(3×1)+4], 10 [=(3×2)+4], 13 [=(3×3)+4]…
p:nth-child(n) = 每個<p>元素
p:nth-child(1) or p:nth-child(0n+1) = 表示第1個元素,= first-child
p:nth-child(n+8):nth-child(-n+15) = 表示第8到第15元素
first-child 第一個物件樣式設定
last-child 最後一個物件樣式設定
PS.IE8以上支援
tr:nth-child(1){ background-color:#69C; }
nth-of-type()
:nth-of-type(<nth>)
where
<nth>= <an-plus-b>| even | odd
範例應用
參考:https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-of-type
/* Odd paragraphs */ p:nth-of-type(2n+1) { color: red; } /* Even paragraphs */ p:nth-of-type(2n) { color: blue; } /* First paragraph */ p:nth-of-type(1) { font-weight: bold; } /* This has no effect, as the .fancy class is only on the 4th p element, not the 1st */ p.fancy:nth-of-type(1) { text-decoration: underline; }
<div> <div>無效果套用</div> <p>我是p:nth-of-type(1)結果</p> <p>我是p:nth-of-type(2n)結果</p> <div>無效果套用</div> <p>我是p:nth-of-type(2n+1)結果</p> <p class="fancy">無效果套用,p.fancy:nth-of-type(1)為第1個p元素,本.fancy元素為第4個p元素=p.fancy:nth-of-type(4)</p> </div>