Simon Simon - 1 month ago 5
HTML Question

Specific table layout

I want to make an adaptive table with vertical left header row on mobile like this:

Header 1 data data data
Header 2 data data data
Header 3 data data data


And normal table for desktop like this:

Header 1 Header 2 Header 3
data data data
data data data


Has anybody ideas how can I do this only with CSS and HTML (I want to make table so it can be easy to add new rows by PHP).

Answer

You can use mediaqueries and reset display values to the table elements:

table {
  table-layout:fixed;
  border-collapse:collapse;/* whatever */
}
th, td {
  width:100px;/* whatever */
  border:solid;/* See me */
}
th {
  color:#145492
}
@media all and (max-width : 640px) {
  table {
    width:100%;/* whatever needed */
  }
  tbody {
    display:table-row;/* optionnal*/
  }
  tr {
    display:table-cell;    
  }
  th, td {
    display:block;
    width:auto;/* reset width if needed */
  }
}
tr:last-of-type {
  text-align:center;
  text-shadow:1px 1px tomato;
  }
<table>
  <tr>
    <th>header</th>
    <td>data</td>
    <td>data</td>
    <td>data</td>
  </tr>
  <tr>
    <th>header</th>
    <td>data</td>
    <td>data</td>
    <td>data</td>
  </tr>
  <tr>
    <th>header</th>
    <td>test snippet</td>
    <td>in full</td>
    <td>page mode</td>
  </tr>
</table>

edit, just noticed layout is the other way round. maybe you can produce your HTML, so i can update the snippet, anyhow, the method is there whatever the structure will be like ;)

thank you