How to Fit Table Column to Content Width in Tailwind


How can we set a specific table column to fit the width of its contents?

Suppose we have a table in our DOM that looks something like this:

<table>
  <tr>
    <td>Text</td>
    <td>Text</td>
    <td class="stop-stretching">Button</td>
  </tr>
</table>

We want the .stop-stretching class to, well, not stretch. We want it to fit to the content of its cell.

1. Fit table column to cell width in CSS

We can fit the column to the width of the cell in CSS by setting the width to 1% and ensuring white-space: nowrap.

.stop-stretching {
  width: 1%;
  white-space: nowrap;
}

We can also achieve this using width: 1px.

.stop-stretching {
  width: 1px;
  white-space: nowrap;
}

These solutions make the assumption that the contents of the cell will be wider than 1% or 1px.

2. Fit table column to cell width with TailwindCSS

We can easily achieve this in TailwindCSS, but there is no class for width: 1%.

We’ll need to head over to tailwind.config.js to add this class.

module.exports = {
  // ...
  theme: {
    extend: {
      width: {
        '1/100': '1%'
      }
    }
  },
  // ...
}

Then, we can apply our utility classes for the 1%.

<table>
  <tr>
    <td>Text</td>
    <td>Text</td>
    <td class="whitespace-nowrap w-1/100">Button</td>
  </tr>
</table>

Or the 1px.

<table>
  <tr>
    <td>Text</td>
    <td>Text</td>
    <td class="whitespace-nowrap w-px">Button</td>
  </tr>
</table>