1、单行变色
先从简单的单行变色说起。
这个很简单,如果只是固定一行变色,只需要把该行的行数写在css中即可。
例如,只设定第六行变色,代码应写成,
tr:nth-child(6) {
background: #f5fffa;
}
效果如下图:

单行变色
2、单行交替变色
再说说单行交替变色。
在html中,常用表格显示数据。表格的每一行交替使用两种颜色,使得表格数据更易观察。如下图:

单行交替变色
常规数据,控制奇偶行数来表现即可。
tr:nth-child(even) {
background: #f5fffa;
}
或者
tr:nth-child(odd) {
background: #f5fffa;
}
都可以实现上面表格样式。

单行交替变色写法1
tr:nth-child(even) {
background: #f5fffa;
}
代码中even表示偶数行,也可用2n来表示,即,
tr:nth-child(2n) {
background: #f5fffa;
}
tr:nth-child(odd) {
background: #f5fffa;
}
代码中odd表示偶数行,也可用2n+1或者2n-1来表示,即,
tr:nth-child(2n+1) {
background: #f5fffa;
}
或者
tr:nth-child(2n-1) {
background: #f5fffa;
}
效果如下图,代码见图下方调试器红线框内:

单行交替变色写法2
3、多行交替变色
现在来说说多行交替变色。
如果现在的特殊需求是三行一变色呢?肯定有人想是不是和3n有关啊,三行一个颜色嘛……
其实不然。先来看看效果图:

三行交替变色
三行一变色,其实质是,第一组第一次变成绿色,到下一组第一次变成绿色,中间相差六条数据,也就是6个,所以三行一变色并不是与3n有关,而是与6n有关系,其代码应该写成,
tr:nth-child(6n+1) {
background: #f5fffa;
}
tr:nth-child(6n+2) {
background: #f5fffa;
}
tr:nth-child(6n+3) {
background: #f5fffa;
}
效果如下图:

三行交替变色写法
同理可推知,四行一变色的代码应该是:
tr:nth-child(8n+1) {
background: #f5fffa;
}
tr:nth-child(8n+2) {
background: #f5fffa;
}
tr:nth-child(8n+3) {
background: #f5fffa;
}
tr:nth-child(8n+4) {
background: #f5fffa;
}
效果如下图:

四行交替变色写法