Lattice Grid Buy a licence

demo D14

Auto-size and fit

Size a column to its content, or fit every column to the viewport

columns.autoSize() · columns.fit()

Building…
Loading a live grid…

The configuration

<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@toclocoinc/lattice-grid@1.13.0/lattice-grid.min.css">
<script src="https://cdn.jsdelivr.net/npm/@toclocoinc/lattice-grid@1.13.0/lattice-grid.min.js"></script>

<div id="grid" style="height: 540px"></div>

<script>
  const grid = LatticeGrid.createGrid(document.getElementById('grid'), {
    rowKey: 'id',
    columns: [
      { field: 'service', title: 'Service', layout: { width: 150 } },
      { field: 'team', title: 'Team', layout: { width: 150, min: 90 } },
      { field: 'region', title: 'Region', layout: { width: 150 } },
      { field: 'repository', title: 'Repository', layout: { width: 150, max: 340 } },
    ],
    rows,  // 5,000 service records
  });

  // fit() divides the viewport between the columns and honours each min and
  // max. Deferred one frame, because it needs the grid laid out before it has
  // a width to divide; call it again after the data changes to refit.
  requestAnimationFrame(() => grid.columns.fit?.());
</script>

Auto-sizing columns to content in a JavaScript data grid

Auto-size measures the widest rendered value in a column, including its header, and sets the column to that width so nothing truncates and nothing sits in unused space. Reach for it after loading a dataset whose value lengths are not known at configuration time, such as a lookup column whose labels come from an API or a numeric column whose formatted width depends on locale. columns.autoSize() runs the measurement for one column, a list of columns, or the whole set, and only touches the columns named in the call, so a wide description column can be left alone while numeric columns beside it tighten to their content.

columns.fit() solves a different problem: distributing the full viewport width across the visible columns so the grid has no empty strip on the right and no horizontal scrollbar when the content would otherwise fall short of the container. The two are commonly chained, auto-sizing first to establish a fair starting width per column, then fitting to absorb whatever width remains. Measurement happens against the cells currently in the DOM under virtual scrolling, not the full row set, so auto-sizing a column in a one-million-row grid costs the same as in a hundred-row one, bounded by rows in the viewport rather than rows in the store.

How do you auto-size a column to fit its content in a JavaScript data grid?

Call columns.autoSize() with a column ID, an array of IDs, or no argument to size every column, and the grid measures the widest rendered value per column and sets its width to match. Call columns.fit() afterwards to stretch or compress the resulting widths so the visible columns exactly fill the grid’s width, removing any leftover gap or scrollbar.