I have a table like this:
<p>On large screens</p>
<table>
<tr>
<td>1</td>
<td>3</td>
<td>5</td>
</tr>
<tr>
<td>2</td>
<td>4</td>
<td>6</td>
</tr>
</table>
Is there a way to modify it purely with CSS to LOOK like this? (a single column where every odd item is from the first row and every even is from the second row)
<p>On small screens</p>
<div>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>
</div>
I tried to use display: contents;
but apparently, it does not work on <tr>
-s for some reason. Any ideas on how I should approach this? Also, I can only use pure (S)CSS. The number of rows and columns is dynamic.
Use CSS grid like below
table {
display: grid;
}
table > *, /* you need to target the "tbody" as well as "tr" */
table tr {
display: contents;
}
td:nth-child(1) {order:1}
td:nth-child(2) {order:2}
td:nth-child(3) {order:3}
/* td:nth-child(n) {order:n} */
<p>On large screens</p>
<table>
<tr>
<td>1</td>
<td>3</td>
<td>5</td>
</tr>
<tr>
<td>2</td>
<td>4</td>
<td>6</td>
</tr>
</table>
Or a very hacky way that I don't recommend:
table {
display: grid;
}
table > tbody {
display: contents;
}
/* the hack is here */
table tr {
grid-area: 1/1; /* both tr will overlap */
display: grid;
grid-auto-rows: 2lh; /* you need to make this equal to twice the height of one "td" */
}
/* the second one will show the content at the bottom while the first one will keep the at the top */
table tr:nth-child(2) {
align-items: end;
}
<p>On large screens</p>
<table>
<tr>
<td>1</td>
<td>3</td>
<td>5</td>
</tr>
<tr>
<td>2</td>
<td>4</td>
<td>6</td>
</tr>
</table>