htmlcsszurb-foundationzurb-foundation-6

Responsive table with 100% width


Here's code:

<div class="row">
  <div class="large-12 columns">

    <table class="scroll wide">

      <tr>
        <td>First</td>
        <td>Second</td>
        <td>Third</td>
        <td>Forth</td>
      </tr>

    </table>

  </div>
</div>

CSS

.wide { width: 100%; }

Here's fiddle:

https://jsfiddle.net/emilcieslar/zc37ydys/

As you can see, there are 4 columns and scroll class that makes the table scrollable whenever the width of the page is smaller than the table width. However if I want to make the table width 100%, it stays the same, it doesn't stretch. I can see that the table tag itself is stretched, but the insides doesn't stretch. This is caused by table being display: block, however it has to be display: block, otherwise it won't be scrollable (on horizontal axis). How can I achieve 100% width table while still being responsive?


Solution

  • As they say, think out of the box, so I thought out of the table box and wrapped the table inside a container:

    <div class="horizontal-scroll">
      <table class="my-table"><!-- without scroll class now -->
      ...
      </table>
    </div><!-- /horizontal-scroll -->
    

    with CSS:

    .horizontal-scroll {
      overflow: hidden;
      overflow-x: auto;
      clear: both;
      width: 100%;
    }
    
    .my-table {
      min-width: rem-calc(640);
    }
    

    Incredibly simple solution, but took me a while to realise it. It's important to set min-width for the table as table width is by default flexible therefore it will never scroll if you don't set min-width. It will result in a shrank table to the point it's not possible to shrink anymore.