1.first-child(IE7兼容)、last-child(IE8不兼容)
html:
<body>
<h2>列表</h2>
<ul>
<li>列表項目1</li>
<li>列表項目2</li>
<li>列表項目3</li>
<li>列表項目4</li>
</ul>
</body>
css:
<style>
ul {list-style: none;}
li:first-child {/*給第一個列表項目設置樣式 兼容IE7*/
background-color: pink;
}
li:last-child { /*給最後一個列表項目設置樣式 IE8不兼容*/
background-color: red;
}
</style>
解析:
一個頁面中無論有幾個ul列表,只要設置first-child、last-child,那麼所有ul列表項的第一個和最後一個列表項目都會有設置的樣式。
2.nth-child、nth-last-child (IE8不兼容)
html:
<body>
<h2>列表</h2>
<ul>
<li>列表項目1</li>
<li>列表項目2</li>
<li>列表項目3</li>
<li>列表項目4</li>
<li>列表項目5</li>
<li>列表項目6</li>
</ul>
</body>
css:
<style>
ul {list-style: none;}
li:nth-child(3) { /*表示li元素中,第三個元素 IE8不兼容*/
background-color: pink;
}
li:nth-last-child(2) { /*表示li元素中,倒數第二個元素 IE8不兼容*/
background-color: red;
}
</style>
3.對奇數、偶數使用樣式
html:
<ul>
<li>列表項目1</li>
<li>列表項目2</li>
<li>列表項目3</li>
<li>列表項目4</li>
<li>列表項目5</li>
<li>列表項目6</li>
</ul>
css:
<style>
ul {list-style: none;}
li:nth-child(odd) {/*表示li元素中,從1開始 奇數爲pink*/
background-color: pink;
}
li:nth-child(even) {/*表示li元素中,從1開始 偶數爲灰色*/
background-color: #ccc;
}
</style>
解析: li:nth-child(odd)
含義:li的父元素ul的兒子中,從1開始數,奇數兒子設置樣式爲xxx;
當父元素爲列表時,因爲只有列表項目一種子元素,不會出現問題;當父元素是div時,就不止一種子元素,會引起問題。如下:
例如:設置div元素中爲奇數標題h2背景顏色
html:
<div>
<h2>文章標題A</h2>
<p>我是一個小段落。。。</p>
<h2>文章標題B</h2>
<p>我是一個小段落。。。</p>
<h2>文章標題C</h2>
<p>我是一個小段落。。。</p>
<h2>文章標題D</h2>
<p>我是一個小段落。。。</p>
</div>
css:
h2:nth-child(odd) {
background-color: pink;
}
執行結果爲:
解析: h2:nth-child(odd)含義是:h2的父元素div 的所有兒子中 爲奇數的兒子 設置背景顏色;而不是所有h2中爲偶數的h2設置樣式;
解決方法: nth-of-type可以避免問題產生。
4.nth-of-type(IE8不兼容):只針對同類型的元素進行計算
css:
h2:nth-of-type(odd) { /*所有h2標籤中爲奇數的設置樣式*/
background-color: pink;
}
h2:nth-of-type(even) { /*所有h2標籤中爲偶數的設置樣式*/
background-color: #ccc;
}
解析: h2:nth-of-type(odd)
含義:在所有h2標籤中,只要是奇數h2就設置樣式;只針對h2標籤,與父元素無關;
5、循環使用樣式 li:nth-child(4n+1)
html:
<ul>
<li>列表項目1</li>
<li>列表項目2</li>
<li>列表項目3</li>
<li>列表項目4</li>
<li>列表項目5</li>
<li>列表項目6</li>
<li>列表項目7</li>
<li>列表項目8</li>
<li>列表項目9</li>
<li>列表項目10</li>
<li>列表項目11</li>
<li>列表項目12</li>
</ul>
css:
<style>
ul {list-style: none;}
li:nth-child(4n+1) { /*表示li元素中,4個li爲一組循環 第一個li設置爲*/
background-color: red;
}
li:nth-child(4n+2) { /*表示li元素中,4個li爲一組循環 第二個li設置爲*/
background-color: pink;
}
li:nth-child(4n+3) {
background-color: #ccc;
}
li:nth-child(4n+4) {
background-color: yellow;
}
</style>
解析:
4n含義:四個li元素爲一組循環;
4n+1含義:這一組循環中,第一個樣式;
4n+2含義:這一組循環中,第二個樣式;
4n+3含義:這一組循環中,第三個樣式;
4n+4含義:這一組循環中,第四個樣式;