html - 表格为行应用CSS

标签 html css html-table css-selectors

我正在处理 html 表格,我需要在其中的行上添加背景颜色,但我在该行上没有任何类。我正在尝试使用第 nth-child,但我不确定我的逻辑。

我希望 2 行具有相同的背景颜色,接下来的 2 行应该具有如下图所示的背景颜色 2

enter image description here

tr:nth-child(2n) td {
  background-color: yellow
}

tr:nth-child(2n+1) td {
  background-color: pink
}
<table>
<tr><td>background should come as color1</td></tr>
<tr><td>background should come as color1</td></tr>

<tr><td>background should come as color2</td></tr>
<tr><td>background should come as color2</td></tr>

<tr><td>background should come as color1</td></tr>
<tr><td>background should come as color1</td></tr>

<tr><td>background should come as color2</td></tr>
<tr><td>background should come as color2</td></tr>
</table>
以上是为交替行提供背景颜色

最佳答案

tr {
  background-color: yellow
}

tr:nth-child(4n),
tr:nth-child(4n - 1){
  background-color: red
}
<table>

<tr><td>//background should come as color1</td></tr>
<tr><td>//background should come as color1</td></tr>

<tr><td>//background should come as color2</td></tr>
<tr><td>//background should come as color2</td></tr>

<tr><td>//background should come as color1</td></tr>
<tr><td>//background should come as color1</td></tr>

<tr><td>//background should come as color2</td></tr>
<tr><td>//background should come as color2</td></tr>

</table>

关于html - 表格为行应用CSS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72015663/

相关文章:

jQuery Offcanvas 在响应式网页中不起作用

css - 溢出:隐藏在 Google Chrome 中无法正常工作

html - 将显示设置为表格单元格的内容垂直居中

html rowspan 没有按预期运行

javascript - 创建 div 元素后在其下方保留一个单击按钮

jquery - 使用 CSS3 将 Circle 分成三部分

html - 如何对齐html中的两个文本区域

javascript - HTML 表格到 Excel (xls) 使用 javascript/jQuery

javascript - 添加新输入字段时如何保存现有输入字段中的值?

javascript - 单击复选框清除 contenteditable div 选择