Responsive tables with Sass and CSS3

If you’re working on making your site properly responsive and you’ve got tabular data you’re most likely having trouble figuring out a good way to make the tables responsive. One way is to just let the table get really squished but depending on the data, and number of columns, this completely breaks the display. Another way is to not use table and instead use div but if you need to display tabular data wouldn’t it be nice if you could use the proper HTML for it?

Enter CSS3 and @media queries. @media queries let you define certain blocks of CSS that should only be executed based on your parameters. In this case we’ll be using the width of the window. And because we only want the styles to apply below a certain point we’ll specifically be using max-width to define the maximum width that these styles should apply to.

@media(max-width: 767px) {
  .responsive-table {
    margin: 1em 0;
    min-width: 300px;

    tr {
      border-top: 1px solid #ddd;
      border-bottom: 1px solid #ddd;
    }

    th {
      display: none;
      text-align: left;
    }

    td {
      display: block;
      text-align: left;

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

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

      // These let you optionally flag a column as not having a title. If you don't need this you can
      // drop the &.no-title rules and change the below selector to &:before
      &:not(.no-title):before {
        content: attr(data-title)": ";
        font-weight: bold;
        display: block;
      }

      &.no-title {
        border: 0;
      }
    }
  }
}

If you’re using Bootstrap SASS you can use the variables corresponding to the media query breakpoints instead of hardcoding the maximum width.

To see these in action simply resize your browser and watch the below table of data.

Description Amount Paid On
Payment for adjustments to menu $300 February 4th, 2016
Check payment for balance $750 February 3rd, 2016
Deposit payment $500 January 15th, 2016