Trying to learn HTML and CSS and I have a simple question.
How can I give each row a different color in a table? For example row 1 is red, row 2 is blue etc.
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>
HTML | <tr> bgcolor Attribute The HTML <tr> bgcolor Attribute is used to specify the background color of a table row. It is not supported by HTML 5. Attribute Values: color_name: It sets the background color by using the color name.
You can use the tr:nth-child(rownumber) to color a particular row in a table using CSS. Above code select the 3 row from top (including table head row) and color background as green and foreground as white.
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
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>
You can also try like this
#table tr{background: red;}
#table tr:nth-child(2n+1){background: blue;}
#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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With