CSS中选择奇偶行元素可以让我们在网页设计中实现更多的排版效果,比如斑马线效果、间隔行背景色等。下面介绍三种常见的选择方式。方法一:nthchild选择器li:nthchild(odd) { back...
CSS中选择奇偶行元素可以让我们在网页设计中实现更多的排版效果,比如斑马线效果、间隔行背景色等。下面介绍三种常见的选择方式。
方法一:nth-child选择器
li:nth-child(odd) {
background-color: #F0F0F0; /*奇数行*/
}
li:nth-child(even) {
background-color: #FFFFFF; /*偶数行*/
} 方法二:nth-of-type选择器
li:nth-of-type(odd) {
background-color: #F0F0F0; /*奇数行*/
}
li:nth-of-type(even) {
background-color: #FFFFFF; /*偶数行*/
} 方法三::nth-child(2n+1)选择器
li:nth-child(2n+1) {
background-color: #F0F0F0; /*奇数行*/
}
li:nth-child(2n) {
background-color: #FFFFFF; /*偶数行*/
} 以上三种方法皆可实现选择奇偶行元素,不过建议使用第一种方法,因为它兼容性更好,支持的浏览器更多。同时,可以选择使用nth-child(n)来选择固定几行,比如选择第1行、第3行和第5行:
li:nth-child(1), li:nth-child(3), li:nth-child(5) {
background-color: #F0F0F0;
} 希望本文对大家了解如何选择奇偶行元素在实际网页设计中有所帮助。