3

Is it possible to convert a horizontal table to a vertical one using only CSS?

Here's what I have:

1st header cell 2nd header cell 3rd header cell 4th header cell
1st data cell 2nd data cell 3rd data cell 4th data cell

Here's what I want:

1st header cell | 1st data cell

2nd header cell | 2nd data cell

3rd header cell | 3rd data cell

4th header cell | 4th data cell

My code:

table{
  width: 100%;
  border-collapse: collapse;
}

td, th {
  text-align: left;
  border: 1px solid #ddd;
  padding: 10px;
}
<table>
  <tbody>
    <tr>
      <th>1st header cell</th>
      <th>2nd header cell</th>
      <th>3rd header cell</th>
      <th>4th header cell</th>
    </tr>
    <tr>
      <td>1st data cell</td>
      <td>2nd data cell</td>
      <td>3rd data cell</td>
      <td>4th data cell</td>
    </tr>
  </tbody>
</table>
JOKKER
  • 502
  • 6
  • 21
  • 3
    Don't use a table, use [grid layout](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout) – yaakov Apr 09 '21 at 14:39
  • I haven’t found a general way to do this with only CSS as so much of the structure is in the HTML. If you can’t find a CSS way, a way to do it at run time with a few lines of JS is here [link] https://stackoverflow.com/questions/66986623/i-want-to-change-the-table-from-a-horizontal-group-to-a-vertical-group/66994427#66994427 – A Haworth Apr 09 '21 at 14:43

3 Answers3

8

Without changing your current code, you can shift the orientation of the table using this:

table {
  display: flex;
  align-items: center;
  justify-content: center;
}
tbody {
    display: flex;
    flex-direction: row;
}
tr {
    display: flex;
    flex-direction: column;
}

To adjust the centering of the table content, tweak the align-items and justify-content on the table.

-1

Try this, the table is structured so that each of the data columns are located next to the header cells (horizontally), and each of the columns are stacked vertically.

       <table>
           <tr>
                <th>Header 1</th>
                <td>data cell 1</td><td>data cell 2</td><td>data cell 3</td>
            </tr>
            <tr>
                <th>Header 2</th>
                <td>data cell 1</td><td>data cell 2</td><td>data cell 3</td>
            </tr>
            <tr>
                <th>Header 2</th>
                <td>data cell 1</td><td>data cell 2</td><td>data cell 3</td>
            </tr>
        </table>
Bobby S
  • 27
  • 5
-1

There aren't any recommended CSS solutions for this, definitely not a "standard" one.

But there IS in fact at least one CSS workaround solution (with float): http://jsfiddle.net/XKnKL/3/

tr { display: block; float: left; }
th, td { display: block; }
<table>
  <tbody>
    <tr>
      <th>1st header cell</th>
      <th>2nd header cell</th>
      <th>3rd header cell</th>
      <th>4th header cell</th>
    </tr>
    <tr>
      <td>1st data cell</td>
      <td>2nd data cell</td>
      <td>3rd data cell</td>
      <td>4th data cell</td>
    </tr>
  </tbody>
</table>