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;}
复制代码
解析:由于div元素下奇数元素为 p,偶数元素为后,故 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 含义:这一组循环中,第四个样式;
拓展阅读
评论