Reputation: 27822
I have a table of hundreds of short rows, and I would like to display the rows in columns rather than all underneath each other, like so:
I know I can create two tables and align them, but I would prefer it to be a single table for accessibility purposes, so the HTML of the above would be something like:
<table>
<thead>
<tr><th>Col 1</th><th>Col 2</th></tr>
</thead>
<tbody>
<tr><td>Row 1 Col 1</td><td>Row 1 Col 2</td></tr>
<tr><td>Row 2 Col 1</td><td>Row 2 Col 2</td></tr>
<tr><td>Row 3 Col 1</td><td>Row 3 Col 2</td></tr>
<tr><td>Row 4 Col 1</td><td>Row 4 Col 2</td></tr>
</tbody>
</table>
The closest I've managed to get is by adding multiple tbody elements and aligning them with flexbox (see below), but this has the downside that the header and caption won't be displayed correct:
I can fix that with some HTML/CSS-fu, or by removing the thead and inserting the header elements inside the tbody (without thead), but it seems rather ugly.
Is there a more straightforward way to produce multi-column tables like this? I don't really see anything obvious in the HTML specification.
<style>
table { border-collapse: collapse; }
td { border: 1px solid #000; }
table { display: flex; justify-content: flex-start; }
tbody { margin-right: 1em; }
</style>
<table>
<caption>Table test</caption>
<thead>
<tr><th>Col 1</th><th>Col 2</th></tr>
</thead>
<tbody>
<tr><td>Row 1 Col 1</td><td>Row 1 Col 2</td></tr>
<tr><td>Row 2 Col 1</td><td>Row 2 Col 2</td></tr>
</tbody>
<tbody>
<tr><td>Row 3 Col 1</td><td>Row 3 Col 2</td></tr>
<tr><td>Row 4 Col 1</td><td>Row 4 Col 2</td></tr>
</tbody>
</table>
Upvotes: 3
Views: 1720
Reputation: 9130
Edit: Complete re-write using as much of your HTML as possible. Removed the last answer too.
This version will dynamically scale to suit the page, but you will need to let the CSS know at what screen size you want it to change. Currently set to 520px
.
You will need to copy and paste the code to a test page and resize the window to see the dynamic sizing.
table {
width:100%;
max-width:520px;
text-align:center;
}
.tWide {
display:none;
}
@media all and (min-width:520px) {
thead tr, .tWide {
display:inline-block;
width:46%;
}
thead tr th {
display:inline-block;
width:46%;
text-align:center;
}
tbody {
display:inline-block;
width:46%;
}
td, th { width:23%; }
}
<table>
<caption>Table test</caption>
<thead>
<tr><th>Col 1</th><th>Col 2</th></tr>
<tr class="tWide"><th>Col 1</th><th>Col 2</th></tr>
</thead>
<tbody>
<tr><td>Row 1 Col 1</td><td>Row 1 Col 2</td></tr>
<tr><td>Row 2 Col 1</td><td>Row 2 Col 2</td></tr>
</tbody>
<tbody>
<tr><td>Row 3 Col 1</td><td>Row 3 Col 2</td></tr>
<tr><td>Row 4 Col 1</td><td>Row 4 Col 2</td></tr>
</tbody>
</table>
Upvotes: 2