I am attempting to "group" a collection of cells/<td>
elements within a row/<tr>
in a <table>
in order to apply styles to them. The code below accomplishes what I desire to some extent, but it does have its limitations:
/* Issues with styling */
.row td:not(:first-child) {
background-color: lightgray;
/* possibly a box-shadow */
}
.row td:nth-child(2) {
border-top-left-radius: 10px;
border-bottom-left-radius: 10px;
}
.row td:last-child {
border-top-right-radius: 10px;
border-bottom-right-radius: 10px;
}
/* Fundamental table styles for a decent appearance */
table {
margin: 0 auto;
font-size: 20px;
border-collapse: separate;
border-spacing: 0 1em;
}
table td {
padding: 10px;
}
<table>
<thead>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
</thead>
<tbody>
<tr class="row">
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
</tr>
<tr class="row">
<td>5</td>
<td>6</td>
<td>7</td>
<td>8</td>
</tr>
</tbody>
</table>
The above method achieves the visual effect I desire (except for a box-shadow surrounding the grey box for each group), where the last 3 cells of each row are grouped together. However, there are a few drawbacks:
Styling the last three cells individually requires changing the style of each
<td>
, making styling laborious (e.g., specifying border radius for each corner rather than one simpleborder-radius
style for the entire group).Styling the table this way makes it difficult to add cell spacing between each cell or create a box-shadow that surrounds the entire grey box grouping the last three cells. Applying box-shadow to each
<td>
separately results in each cell appearing distinct, unlike the desired look of a single shadow around the group.
Is there a way to collectively group <td>
s and apply styles holistically to the group instead of individual cells? Ideally, I would like to:
<tr class="row">
<td>1</td>
<div class="row-group">
<td>2</td>
<td>3</td>
<td>4</td>
</div>
</tr>
Then, I could apply border-radius: 10px
, background-color: lightgray
, and box-shadow
styles to the .row-group
class. Unfortunately, the HTML specification does not allow <div>
elements within <tr>
s, rendering this approach ineffective. Exploring <colgroup>
and <col>
tags also proves unhelpful as they primarily affect column-wise styling rather than grouping cells per row. Another consideration is using a sub-table, although I wonder if there exists a simpler solution to achieve grouping and styling these <td>
s collectively, potentially utilizing <col>
s?