Tables troubles - how to make the table behave according to our expectations

Damian Wróblewski - April 2022

Tables troubles - how to make the table behave according to our expectations

Table of contents

  1. Table layout
  2. Sticky header and column

Once upon a time, before the era of flexbox, grid and dinosaurs, tables were the only way to build web page layouts. After the introduction of the mentioned tools, tables fell into disfavor to the point that the table tags caused revulsion among some developers, who stopped using them even to create tables(!). However, I'm convinced that tables will stay with us as long as people want to present data in this way, which is... (spoiler alert!) ... probably forever. Therefore, in this post we will take a closer look at the tables and we will try to create a table that will behave according to our expectations.

Table layout

The most important CSS rule that defines how a table behaves is table-layout. This property is responsible for how the width of the table columns and cells is determined.

There are two key values: auto and fixed.

In simplest terms:

auto - default value, cell width adapts to the content

fixed - this value causes the cell contents to be ignored and instead the table width, explicit column width, and spacing within the cell are taken into account

Important: For fixed value to have any effect, the table width must be set to a value other than the default auto

As you can check in the playground below, when we set the value auto, the cells will adjust their width to match the content and when we set fixed they will be of equal width:

Sticky header and column

Very often we may encounter requirements for tables to set a sticky head when scrolling vertical or one or more sticky columns when scrolling horizontal.

We need to keep a few things in mind here:

  • for the position: sticky rule to work, we need to specify one of the top, bottom, right or left properties as well

  • if you want the sticky elements to keep the border, you should use border-collapse: collapse instead of border-collapse: separate and set the border for each side accordingly

  • it is possible to set both sticky head and column, but remember to set a higher z-index for thead element to always be on top

    You can test how position: sticky works in the playground below:

If you found inaccuracies in this post or know other useful tips or tricks for building flexible tables, please leave a comment below 😉


Join the discussion