Ordering tabular data with only CSS thanks to CSS Variables

Neat experiment by Roman Komarov in which he orders tabular data using just HTML/CSS, thanks to the use of CSS Custom Properties (CSS Variables):

Each cell of each row is given a specific value to sort on.

<tr
  class="table-row"
  style="
    --order-by-published: 161221;
    --order-by-views: 2431;
  ">
  <th class="table-cell">
    <a href="http://kizu.ru/en/fun/controlling-the-specificity/">Controlling the Specificity</a>
  </th>
  <td class="table-cell">2016-12-21</td>
  <td class="table-cell">2 431</td>
</tr>

When selecting a specific column, that value is aliased to the --order CSS Variable

#sort-by-published:checked ~ .table > .table-body > .table-row {
  --order: var(--order-by-published);
}

#sort-by-views:checked ~ .table > .table-body > .table-row {
  --order: var(--order-by-views);
}

And that --orderorder of each row:

.table-row {
  order: var(--order);
}

Add in an extra condition to use in the calculation and you can achieve a reverse sorting:

.table-row {
  order: calc(var(--order) * var(--sort-order, -1));
}

Very nice!

As Roman notes though, this isn’t great when it comes to a11y:

This so­lu­tion is not re­ally a so­lu­tion, but an ex­per­i­ment, and can be bad for ac­ces­si­bil­ity — right now its not pos­si­ble to re­order stuff in a way it would be ac­ces­si­ble with key­board (with­out con­fus­ing tele­port­ing fo­cus) or screen read­ers.

Roman Komarov: Variable Order →

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.