在HTML和CSS中更改表格中行的颜色 [英] change color of rows in a table in HTML and CSS

查看:1109
本文介绍了在HTML和CSS中更改表格中行的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Trying to learn HTML and CSS and I have a simple question.

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

How can I give each row a different color in a table? For example row 1 is red, row 2 is blue etc.

这是我的HTML代码:

This is my HTML code:

#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>

推荐答案

如果我正确理解了您的问题,并且希望为每行赋予不同的颜色?您有几种选择...

If I understand your question correctly and you want to give every row a different color? You have a few options...

  • 为每行添加一个类并为其设置样式.
  • 使用直接兄弟选择器tr + tr
  • 使用:nth-of-type
  • Add a class to each row and style those.
  • Use the direct sibling selector tr + tr
  • Use :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和CSS中更改表格中行的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆