css中 如何选择奇偶行元素

admin 轻心小站 关注 LV.19 运营
发表于前端技术学习版块 css,教程

CSS中选择奇偶行元素可以让我们在网页设计中实现更多的排版效果,比如斑马线效果、间隔行背景色等。下面介绍三种常见的选择方式。方法一:nth-child选择器li:nth-child(odd) { ba

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;
} 

希望本文对大家了解如何选择奇偶行元素在实际网页设计中有所帮助。

文章说明:

本文原创发布于探乎站长论坛,未经许可,禁止转载。

题图来自Unsplash,基于CC0协议

该文观点仅代表作者本人,探乎站长论坛平台仅提供信息存储空间服务。

评论列表 评论
发布评论

评论: css中 如何选择奇偶行元素

粉丝

0

关注

0

收藏

0

已有0次打赏