Fixed Table Layouts

Avatar of Chris Coyier
Chris Coyier on (Updated on )

📣 Freelancers, Developers, and Part-Time Agency Owners: Kickstart Your Own Digital Agency with UACADEMY Launch by UGURUS 📣

There is a CSS property for tables that, it seems to me, is well-supported, little known, and super useful. It changes the way that tables are rendered such that it gives you a sturdier, more predictable layout.

It is this:

table {
  table-layout: fixed;
}

The default property for table-layout is auto, and that is the table layout I think most of us are familiar with. That style, to me, feels spongy and weird. Here’s an exploration:

See the Pen Default Tables are Weird. by Chris Coyier (@chriscoyier) on CodePen.

With table-layout: fixed;

Things get a lot sturdier and more predictable with property/value in place.

The layout is fixed based on the first row. Set the width of those, and the rest of the table follows.

It’s a little more complicated, but not much. Here’s an exploration:

See the Pen Fixed Tables Solve Some Issues by Chris Coyier (@chriscoyier) on CodePen.

Use Case

I explored this because I was trying to keep a uniform row height for Pens in list view on CodePen (i.e. not wrap Pen titles) but also not blow out the width of the table. This worked great.

I imagine most of you know this: tables are for tabular data and emails. Not web layouts, because reasons.

Practical HTML and CSS

I imagine most uses will be like this:

<table class="users">
  <thead>
    <tr>
      <th class="row-1 row-ID">ID</th>
      <th class="row-2 row-name">Name</th>
      <th class="row-3 row-job">Job</th>
      <th class="row-4 row-email">Email<th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>0001</td>
      <td>Johnny Five</td>
      <td>Robotin'</td>
      <td>[email protected]</td>
    </tr>
    <tr>
      <td>0002</td>
      <td>Super Superlonglastnamesmith</td>
      <td>Doin' stuff</td>
      <td>[email protected]</td>
    </tr>
  </tbody>
</table>
.users {
  table-layout: fixed;
  width: 100%;
  white-space: nowrap;
}
.users td {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* Column widths are based on these cells */
.row-ID {
  width: 10%;
}
.row-name {
  width: 40%;
}
.row-job {
  width: 30%;
}
.row-email {
  width: 20%;
}

See the Pen xFcrp by Chris Coyier (@chriscoyier) on CodePen.

For good measure, know that you can use the <col> element to set column widths too, because those effect the first row of cells and it’s all about that first row of cells setting the basis for the rest of the table.

Layout Speed

I’ve heard that this style of table layout is faster as well, which stands to reason because the contents of the entire table don’t need to be analyzed to know how big column widths are going to be. I don’t have any data on that though.

In Emails

Campaign Montior’s support chart for CSS in email clients shows table-layout as being supported across the board.

More Info

Follow Up Tweets