Maria Warnes

ACF Table Field Responsive Layout

I came across this cool CodePen for a responsive layout table recently by Geoff Yuen that uses content: attr('data-attr'); to supply each td with it’s relevant th. I had an opportunity to use this method the other day but we were using the ACF Table Field which meant modifying the code slightly. You can find the results below:


<?php $table = get_field('specification');

if ($table) {
  echo '<table border="0">';

    if ($table['header']) {
      echo '<thead>';
        echo '<tr>';
          foreach ($table['header'] as $th) {
            echo '<th>';
              echo $th['c'];
            echo '</th>';
          }
        echo '</tr>';
      echo '</thead>';
    }

  echo '<tbody>';
    foreach ($table['body'] as $tr) {
      echo '<tr>';
      $i = 0;
      foreach ($tr as $td) {
        echo '<td data-column="' . $table['header'][$i]['c'] . ':">';
          echo $td['c'];
        echo '</td>';
        $i++;
      }
      echo '</tr>';
    }
   echo '</tbody>';

  echo '</table>';
} ?>

@breakpoint: 480px;

table {
  th {
    display: none;
  }

  td {
    display: block;

    &:first-child {
      padding-top: .5em;
    }

    &:last-child {
      padding-bottom: .5em;
    }

    &:before {
      content: attr(data-th)": ";
      font-weight: bold;

      @media (min-width: @breakpoint) {
        display: none;
      }
    }
  }

  th, td {
    text-align: left;

    @media (min-width: @breakpoint) {
      display: table-cell;
      padding: .25em .5em;

      &:first-child {
        padding-left: 0;
      }

      &:last-child {
        padding-right: 0;
      }
    }
  }
}