Lynn Chen Lynn Chen - 1 month ago 7
Sass (Sass) Question

CSS display table vertically and expand horizontally when overflow

I have a table:

<table>
<tbody>
<tr>
<th>title</th>
<td>1</td>
<td>2</td>
<td>3</td>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
</tbody>
</table>


, and I want display the table like this:

+-----------+
| title |
+-----+-----+
| 1 | 4 |
+-----+-----+
| 2 | 5 |
+-----+-----+
| 3 | 6 |
+-----+-----+


How do I get this done with css/sass without using javascript and changing HTML structure?

Answer

Use css3 Columns with following HTML structure:

<ul>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  ....
  ....
  <li>n</li>
</ul>

With css as below:

.custom-list {
  list-style: none;
  column-gap: 0;
  column-count: 2;
}

.custom-list {
  text-align: center;
  float: left;
  list-style: none;
  column-gap: 0;
  column-count: 2;
  padding: 0;
  margin: 0;
}
.custom-list li {
  border: 1px solid #000;
  width: 32px;
}
<div class="title">title</div>
<ul class="custom-list">
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
</ul>

However if you can't change structure you need to override default behavior of <tr> and <td> and apply css3 columns here as well.

.custom-table {
  text-align: center;
}
.custom-table thead th {
  text-align: left;
}
.custom-table tbody tr {
  column-count: 2;
  column-gap: 0;
  display: block;
}
.custom-table tbody tr td {
  border: 1px solid #000;
  min-width: 32px;
  display: block;
}
<table class="custom-table">
  <thead>
    <tr>
      <th colspan="2">title</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
    </tr>
  </tbody>
</table>