Divya
Divya

Reputation: 184

How to convert rows to columns using CSS?

I'm developing a Web Application in Ionic3 framework. In my table Each item is available in different sizes. On mobile devices, the screen is too narrow to properly display up to 4 different sizes item.

So I would like to convert rows into columns in Mobile view only.

Let's take this Example

Input-

x1 | x2 | x3 | x4 | x5

y1 | y2 | y3 | y4 | y5

z1 | z2 | z3 | z4 | z5

Output-

x1 | y1 | z1

x2 | y2 | z2

x3 | y3 | z3

x4 | y4 | z4

x5 | y5 | z5

Is there a way of doing this in CSS?

Upvotes: 1

Views: 9909

Answers (2)

Reishabh
Reishabh

Reputation: 195

This can be easily done using HTML and css

table,
th,
td {
  border: 1px solid #000;
}

table {
  max-width: 100%;
}

@media screen and (max-width:767px) {
  table tr>* {
    display: block;
  }
  table tr {
    display: table-cell;
    vertical-align: top;
  }
}
<table>
  <tr>
    <th>Head 1</th>
    <th>Head 2</th>
    <th>Head 3</th>
    <th>Head 4</th>
    <th>Head 5</th>
    <th>Head 6</th>
    <th>Head 7</th>
  </tr>
  <tr>
    <td>Row 1 Cell 1</td>
    <td>Row 1 Cell 2</td>
    <td>Row 1 Cell 3</td>
    <td>Row 1 Cell 4</td>
    <td>Row 1 Cell 5</td>
    <td>Row 1 Cell 6</td>
    <td>Row 1 Cell 7</td>
  </tr>
</table>

Upvotes: 1

Ihor
Ihor

Reputation: 1244

You can do it using display: flex.

@media screen and (max-width: 500px) {
  tr {
    display: inline-flex;
    flex-direction: column;
  }
}
<table>
  <tr>
    <td>x1</td>
    <td>x2</td>
    <td>x3</td>
    <td>x4</td>
    <td>x5</td>
  </tr>
  <tr>
    <td>y1</td>
    <td>y2</td>
    <td>y3</td>
    <td>y4</td>
    <td>y5</td>
  </tr>
  <tr>
    <td>z1</td>
    <td>z2</td>
    <td>z3</td>
    <td>z4</td>
    <td>z5</td>
  </tr>
</table>

Upvotes: 6

Related Questions