html - 在 HTML 和 CSS 中更改表格中行的颜色

标签 html css

尝试学习 HTML 和 CSS,我有一个简单的问题。

如何为表格中的每一行指定不同的颜色?例如第 1 行是红色,第 2 行是蓝色等。

这是我的 HTML 代码:

#table {
  font-family: Arial, Helvetica, sans-serif;
  width: 600px;
  border-collapse;
  collapse;
}
#table td,
#table th {
  font-size: 12x;
  border: 1px solid #4D365B;
  padding: 3px 7px 2px 7px;
}
#table th {
  font-size: 14px;
  text-align: left;
  padding-top: px;
  padding-bottom: 4px;
  background-color: #4D365B;
  color: #918CB5;
}
#table td {
  color: #000000;
  background-color: #979BCA;
}
<table id="table">
  <tr>
    <th>Company</th>
    <th>Contact
      <th>Country</th>
  </tr>
  <tr>
    <td>1</td>
    <td>2
      <td>3</td>
  </tr>
  <tr>
    <td>1</td>
    <td>2
      <td>3</td>
  </tr>
  <tr>
    <td>1</td>
    <td>2
      <td>3</td>
  </tr>
</table>

最佳答案

如果我对您的问题的理解正确并且您想为每一行赋予不同的颜色?您有几个选择...

  • 为每一行添加一个类并设置它们的样式。
  • 使用直接兄弟选择器 tr + tr
  • 使用:nth-of-type

table tr {background: red;}
table tr:nth-of-type(2) {background: blue;}
table tr:nth-of-type(3) {background: green;}
table tr:nth-of-type(4) {background: yellow;}
table tr:nth-of-type(5) {background: grey;}
<table id="table">
  <tr>
    <th>Company</th>
    <th>Contact
      <th>Country</th>
  </tr>
  <tr>
    <td>1</td>
    <td>2
      <td>3</td>
  </tr>
  <tr>
    <td>1</td>
    <td>2
      <td>3</td>
  </tr>
  <tr>
    <td>1</td>
    <td>2
      <td>3</td>
  </tr>
  <tr>
    <td>1</td>
    <td>2
      <td>3</td>
  </tr>
</table>

关于html - 在 HTML 和 CSS 中更改表格中行的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32818958/

相关文章:

php - 正则表达式跳过一个标签,如果它在另一个标签内

javascript - 如何在vue中制作 table 前的徽章?

javascript - 组合 JavaScript 函数

html - CSS 背景图片幻灯片

html - 如何在 StackOverflow 中实现代码显示样式?

html - 如何解决跨域安全错误。在 html 5 中使用 Canvas.getImageData

jQuery 选择器 nth-child(n) 处于未知级别?

html - 居中图像并保持导航可见

javascript - css position 伪元素堆叠

css - CSS3 有不同的标记吗?