Is there a way to color spans of columns all the way down. See, starting example below:
<table border="1">
<tr>
<th>Motor</th>
<th colspan="3">Engine</th>
<th>Car</th>
<th colspan="2">Body</th>
</tr>
<tr>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
<td>7</td>
</tr>
<tr>
<td>7</td>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
</table>
And I am looking for a better way (less code, non-individual coloring) to color, for example, "Engine" and "Body" spans, including all the cells underneath them in #DDD
<style>
.color {
background-color: #DDD
}
</style>
<table border="1">
<tr>
<th>Motor</th>
<th colspan="3" class="color">Engine</th>
<th>Car</th>
<th colspan="2" class="color">Body</th>
</tr>
<tr>
<td>1</td>
<td class="color">2</td>
<td class="color">3</td>
<td class="color">4</td>
<td>5</td>
<td class="color">6</td>
<td class="color">7</td>
</tr>
<tr>
<td>7</td>
<td class="color">1</td>
<td class="color">2</td>
<td class="color">3</td>
<td>4</td>
<td class="color">5</td>
<td class="color">6</td>
</tr>
</table>
In HTML, table background color is defined using Cascading Style Sheets (CSS). Specifically, you use the background-color property to define background color. You can apply this property against the whole table, a row, or a single cell.
Cell background colors are set by applying the bgcolor attribute to a <tr> tag (to color the row) or to a <td> tag (to color the cell).
Yes, you can... using the <col>
element:
.grey {
background-color: rgba(128,128,128,.25);
}
.red {
background-color: rgba(255,0,0,.25);
}
.blue {
background-color: rgba(0,0,255,.25);
}
<table>
<colgroup>
<col class="grey" />
<col class="red" span="3" />
<col class="blue" />
</colgroup>
<thead>
<tr>
<th>#</th>
<th colspan="3">color 1</th>
<th>color 2</th>
</tr>
</thead>
<tbody>
<tr>
<th>1</th>
<td>red</td>
<td>red</td>
<td>red</td>
<td>blue</td>
</tr>
<tr>
<th>2</th>
<td>red</td>
<td>red</td>
<td>red</td>
<td>blue</td>
</tr>
</tbody>
</table>
Note: You can use the span
attribute to make the col definition apply to more than one column.
See also: <colgroup>
You can use the nth-child
selector for that:
tr td:nth-child(2),
tr td:nth-child(3) {
background: #ccc;
}
<table>
<tr>
<th colspan="2">headline 1</th>
<th>headline 2</th>
</tr>
<tr>
<td>column 1</td>
<td>column 2</td>
<td>column 3</td>
</tr>
<tr>
<td>column 1</td>
<td>column 2</td>
<td>column 3</td>
</tr>
<tr>
<td>column 1</td>
<td>column 2</td>
<td>column 3</td>
</tr>
</table>
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