If you want to color different groups (rows, columns, or sections) in an HTML table, here are a few common approaches.
1. Color Row Groups
<table border="1" style="border-collapse: collapse; width:100%;">
<tr style="background-color:#4CAF50; color:white;">
<th>Name</th>
<th>Department</th>
<th>Salary</th>
</tr>
<!-- Group 1 -->
<tr style="background-color:#E8F5E9;">
<td>John</td>
<td>HR</td>
<td>$4,000</td>
</tr>
<tr style="background-color:#E8F5E9;">
<td>Sarah</td>
<td>HR</td>
<td>$4,500</td>
</tr>
<!-- Group 2 -->
<tr style="background-color:#E3F2FD;">
<td>Mike</td>
<td>IT</td>
<td>$5,200</td>
</tr>
<tr style="background-color:#E3F2FD;">
<td>Emma</td>
<td>IT</td>
<td>$5,600</td>
</tr>
</table>
2. Use <tbody> to Group Rows
<table class="group-table">
<thead>
<tr>
<th>Name</th>
<th>Department</th>
<th>Salary</th>
</tr>
</thead>
<tbody class="group1">
<tr><td>John</td><td>HR</td><td>$4000</td></tr>
<tr><td>Sarah</td><td>HR</td><td>$4500</td></tr>
</tbody>
<tbody class="group2">
<tr><td>Mike</td><td>IT</td><td>$5200</td></tr>
<tr><td>Emma</td><td>IT</td><td>$5600</td></tr>
</tbody>
</table>
.group-table {
border-collapse: collapse;
width: 100%;
}
.group-table th,
.group-table td {
border: 1px solid #ccc;
padding: 10px;
}
.group1 {
background-color: #E8F5E9;
}
.group2 {
background-color: #E3F2FD;
}
3. Color Column Groups with <colgroup>
<table border="1">
<colgroup>
<col style="background-color:#FFF3CD;">
<col style="background-color:#D4EDDA;">
<col style="background-color:#D1ECF1;">
</colgroup>
<tr>
<th>Name</th>
<th>Department</th>
<th>Salary</th>
</tr>
<tr>
<td>John</td>
<td>HR</td>
<td>$4000</td>
</tr>
</table>
This colors each column differently.
Common Group Colors
| Group | Color |
|---|---|
| Green | #E8F5E9 |
| Blue | #E3F2FD |
| Yellow | #FFF3CD |
| Orange | #FFE5B4 |
| Purple | #F3E5F5 |
| Gray | #F5F5F5 |
Using CSS classes or <tbody> groups is the most maintainable approach when you have multiple sections that need different colors.

0 Comments