高级前端
css
【Q307】如何实现表格单双行条纹样式

如何实现表格单双行条纹样式

Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 309 (opens in a new tab)

Author 回答者: shfshanyue (opens in a new tab)

通过 css3 中伪类 :nth-child 来实现。其中 :nth-child(an+b) 匹配下标 { an + b; n = 0, 1, 2, ...} 且结果为整数的子元素

  • nth-child(2n)/nth-child(even): 双行样式
  • nth-child(2n+1)/nth-child(odd): 单行样式

其中 tr 在表格中代表行,实现表格中单双行样式就很简单了:

tr:nth-child(2n) {
  background-color: red;
}
 
tr:nth-child(2n + 1) {
  background-color: blue;
}

同理:

  1. 如何匹配最前三个子元素: :nth-child(-n+3)
  2. 如何匹配最后三个子元素: :nth-last-child(-n+3)

Author 回答者: nanwangjkl (opens in a new tab)

不是有odd和even吗

tr:nth-child(even) {
  background: #ccc;
}
tr:nth-child(odd) {
  background: #fff;
}

Author 回答者: songcee (opens in a new tab)

已收到你的邮件,谢谢~~~

Author 回答者: loveminxo (opens in a new tab)

这是来自QQ邮箱的假期自动回复邮件。你好,我最近正在休假中,无法亲自回复你的邮件。我将在假期结束后,尽快给你回复。