CSS: rendere responsive le tabelle

CSS: rendere responsive le tabelle

In questo articolo vedremo come rendere responsive le tabelle con i CSS.

Partiamo dalla seguente tabella:


<table>
  <thead>
  <tr>
    <th>A</th>
    <th>B</th>
    <th>C</th>
  </tr>
  </thead>
  <tbody>
    <!--...-->
  </tbody>
</table>

La soluzione รจ la seguente:


@media screen and (max-width: 768px) {

  table, thead, tbody, th, td, tr { 
    display: block; 
  }
  
  thead tr { 
    position: absolute;
    top: -9999px;
    left: -9999px;
  }
  
  tr { border: 1px solid #ccc; }
  
  td {
    border: none;
    border-bottom: 1px solid #eee; 
    position: relative;
    padding-left: 50%; 
  }

  td:before { 
    position: absolute;
    top: 6px;
    left: 6px;
    width: 45%; 
    padding-right: 10px; 
    white-space: nowrap;
  }

  td:nth-of-type(1):before { content: "A"; }
  td:nth-of-type(2):before { content: "B"; }
  td:nth-of-type(3):before { content: "C"; }
}

Torna su