JarrodOliver JarrodOliver - 5 months ago 12
CSS Question

Mobile responsive table with HTML

I have a table that has 2 header columns and 4 columns of links. Example code below.



table{
border: 1px solid black;
table-layout: fixed;
width:100%
}


th, td{
border: 1px solid black;
overflow: hidden;
}

td {
width:25%;
}


<table class="fixed-width">
<tr>
<th colspan=2>header 1</th>
<th colspan=2>header 234567895678657</th>
</tr>
<tr>
<td>data asdfasdfasdfasdfasdf</td>
<td>data 2</td>
<td>link 3</td>
<td>link 4</td>
</tr>
<tr>
<td>data asdfasdfasdfasdfasdf</td>
<td>data 2</td>
<td>link 3</td>
<td>link 4</td>
</tr>
<tr>
<td>data asdfasdfasdfasdfasdf</td>
<td>data 2</td>
<td>link 3</td>
<td>link 4</td>
</tr>
<tr>
<td>data asdfasdfasdfasdfasdf</td>
<td>data 2</td>
<td>link 3</td>
<td>link 4</td>
</tr>
</table>





https://jsfiddle.net/pse6thr8/21/

I would like the table to look something like this when a mobile accesses it.
New Table

Answer

There are 2 different approaches to do that...

  1. Using Bootstrap columns or
  2. Collapse to Tabs or accordion on smaller view

First check how bootstrap columns will work,

first of all, add Bootstrap.min.css file to your like this,

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">

Check this fiddle

and then your HTML will be like this,

<div class="col-sm-6">

<table class="fixed-width">
   <tr>
      <th colspan=2>header 1</th>
   </tr>
   <tr>
      <td>data asdfasdfasdfasdfasdf</td>
      <td>data 2</td>
   </tr>
   <tr>
      <td>data asdfasdfasdfasdfasdf</td>
      <td>data 2</td>
   </tr>
   <tr>
      <td>data asdfasdfasdfasdfasdf</td>
      <td>data 2</td>
   </tr>
   <tr>
      <td>data asdfasdfasdfasdfasdf</td>
      <td>data 2</td>
   </tr>
</table>
</div>


<div class="col-sm-6">

<table class="fixed-width">
   <tr>
      <th colspan=2>header 234567895678657</th>
   </tr>
   <tr>
      <td>link 3</td>
      <td>link 4</td>
   </tr>
   <tr>
      <td>link 3</td>
      <td>link 4</td>
   </tr>
   <tr>
      <td>link 3</td>
      <td>link 4</td>
   </tr>
   <tr>
      <td>link 3</td>
      <td>link 4</td>
   </tr>
</table>

</div>

and add this css as,

.col-sm-6{
  padding:0px
}
  1. Collapse to Tabs or accordion on smaller view

Check this codepen by csstricks

Comments