html - 如何更改html表格中第一行的背景颜色和所有其他行的替代颜色

标签 html css

我想更改第一行的背景颜色,其下方的所有其余行将是替代颜色,即偶数概念。 目前我正在应用 css 来替代颜色,如下所示:

.table-striped tbody tr:nth-child(odd) td {
    background-color: #81DAF5;
}

.table-striped tbody tr:nth-child(even) td {
    background-color: #CEECF5;
}

.table-striped tbody tr.highlight td {
    background-color: #F2F5A9;
}

这里,.table-striped是表类。那么我怎样才能改变第一行的颜色为不同的颜色,如红色。

上述CSS的输出:

enter image description here

最佳答案

您可以使用:first-child伪类,所有浏览器都支持。

The :first-child CSS pseudo-class represents any element that is the first child element of its parent.

Syntax element:first-child { style properties }

添加到您的 CSS 中:

.table-striped tbody tr:nth-child(odd) td {
  background-color: #81DAF5;
}

.table-striped tbody tr:nth-child(even) td {
  background-color: #CEECF5;
}

.table-striped tbody tr.highlight td {
  background-color: #F2F5A9;
}

.table-striped tbody tr:first-child td {
  background-color: #FF0000;
}

JSFiddle

编辑:如wrick17所述,添加的第一个子规则应放置在底部,否则它会被覆盖。

关于html - 如何更改html表格中第一行的背景颜色和所有其他行的替代颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30557951/

相关文章:

html - 悬停时更改父元素的背景颜色

html - 特定 CSS 选择器 - 环绕元素

html - Bootstrap 复选框按钮显示不正确

javascript - 在页面中创建一个无限滚动的 div

javascript - 访问 jQuery 中的重复标签

javascript - 在内容可编辑的 div 中选择表格?

html - 水平对齐底部和居中?

css - checkbox-inline 将复选框放在文本上而不是旁边

php - 标准化 PHP + CSS 以不使用字符串解析

用于检测系统音量(声音)和插入的音频插孔的 Javascript