DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> DIV十CSS布局 >> 布局實例
CSS3 隔行換色:nth-child 與 nth-of-type 的用法
編輯:布局實例     

列表要隔行換色,過去得在後端跑迴圈判斷奇偶、手動加上 class。CSS3 之後完全不必了,一個 nth-child 就能搞定。

基礎:奇偶分色

#list1 li:nth-of-type(odd)  { background: #00ccff; }  /* 奇數行 */
#list1 li:nth-of-type(even) { background: #ffcc00; }  /* 偶數行 */

odd 與 even 關鍵字是最直觀的寫法,也可以直接用公式 2n+1 與 2n 表達同樣的意思。

進階:4n + N 的循環分色

想要每四個一循環、四種顏色輪替,就用同一組公式搭配不同的餘數:

#list li:nth-child(4n+1) { background: #00ccff; }  /* 從第 1 行起,每 4 個一循環 */
#list li:nth-child(4n+2) { background: #090;    }  /* 從第 2 行起 */
#list li:nth-child(4n+3) { background: #009;    }  /* 從第 3 行起 */
#list li:nth-child(4n+4) { background: #990;    }  /* 從第 4 行起 */

公式怎麼讀?以 4n+1 為例,n 從 0 開始代入,得到 1、5、9、13……也就是「從第 1 行開始,每隔 4 個命中一次」。四條規則合起來,正好不重不落地把所有行分完。

完整示例

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>CSS3 隔行換色測試</title>
<style type="text/css">
#list1 li:nth-of-type(odd)  { background: #00ccff; }
#list1 li:nth-of-type(even) { background: #ffcc00; }

#list2 li:nth-child(4n+1) { background: #00ccff; }
#list2 li:nth-child(4n+2) { background: #090; }
#list2 li:nth-child(4n+3) { background: #009; }
#list2 li:nth-child(4n+4) { background: #990; }
</style>
</head>
<body>
<div>
  <ul id="list1">
    <li>1111111 前端路上是懶人建站的多人博客</li>
    <li>222222222222 CSS3 隔行換色測試</li>
    <li>333333333 提供 jquery 教程實例學習代碼、html5 教程實例和 css/css3 教程實例</li>
    <li>44444444 前端路上博客的靈魂:學習、發現、分享、交流</li>
    <li>55555555555555</li>
    <li>66666666666666666</li>
  </ul>
  <hr />
  <ul id="list2">
    <li>1111111 前端路上是懶人建站的多人博客</li>
    <li>222222222222 CSS3 隔行換色測試</li>
    <li>333333333 提供 jquery 教程實例學習代碼</li>
    <li>44444444 前端路上博客的靈魂</li>
    <li>55555555555555</li>
    <li>66666666666666666</li>
  </ul>
</div>
</body>

nth-child 與 nth-of-type 的差別

兩者容易搞混。nth-child 是按「所有兄弟元素中的第幾個」來算,如果列表裡混進了 ol、div 等其他標籤,計數會被算進去。nth-of-type 則只看同類標籤,比較不受雜項影響。純 li 結構下兩者結果相同,混合內容時建議用 nth-of-type。

另外還有幾個常用變體::first-child、:last-child、:nth-last-child(n)(從後往前數)、:not()(排除條件),組合起來幾乎能應付所有條列樣式的需求。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved