---
product: "AG Grid"
title: "Grid Layout"
description: "Format the grid layout for your JavaScript Table. Change grid width/height, assign a DOM layout value, format dynamic resizing."
framework: javascript
version: "36.2.0"
related:
    - title: "Design System"
      url: "https://www.ag-grid.com/archive/36.2.0/javascript-data-grid/ag-grid-design-system/"
llms: "https://www.ag-grid.com/archive/36.2.0/llms.txt"
---

# Grid Layout

Set the width, height and scrolling behaviour of the grid.

```html
<!-- set width using percentages -->
<div id="myGrid" style="width: 100%; height: 100%;"></div>

<!-- OR set width using fixed pixels -->
<div id="myGrid" style="width: 500px; height: 200px;"></div>
```

> **Warning**
>
> If using % for your height, then make sure the container you are putting the grid into also has height specified, as the browser will fit the div according to a percentage of the parent's height, and if the parent has no height, then this % will always be zero.
>
> If your grid is not the size you think it should be then put a border on the grid's div and see if that's the size you want (the grid will fill this div). If it is not the size you want, then you have a CSS layout issue in your application.

## DOM Layout

There are three DOM Layout values the grid can have 'normal', 'autoHeight' and 'print'. They are used as follows:

- **normal**: This is the default if nothing is specified. The grid fits the width and height of the div you provide and scrolls in both directions.
- **autoHeight**: The grid's height adjusts to fit the number of rows, with optional minimum and maximum height.
- **print**: No scroll bars are used and the grid renders all rows and columns. This layout is explained in [Printing](https://www.ag-grid.com/archive/36.2.0/javascript-data-grid/printing/).

## Normal Layout

If the width and / or height change after the grid is initialised, the grid will automatically resize to fill the new area.

The example below shows setting the grid size and then changing it as the user selects the buttons.

#### Width & Height

```ts
import {
  ClientSideRowModelModule,
  GridApi,
  GridOptions,
  ModuleRegistry,
  createGrid,
  enableDevValidations,
} from "ag-grid-community";
import { IOlympicData } from "./interfaces";

if (process.env.NODE_ENV !== "production") {
  // Enable extended validations only for development
  enableDevValidations();
}

ModuleRegistry.registerModules([ClientSideRowModelModule]);

let gridApi: GridApi<IOlympicData>;

const gridOptions: GridOptions<IOlympicData> = {
  columnDefs: [
    { field: "athlete", width: 150 },
    { field: "age", width: 90 },
    { field: "country", width: 150 },
    { field: "year", width: 90 },
    { field: "date", width: 150 },
    { field: "sport", width: 150 },
    { field: "gold", width: 100 },
    { field: "silver", width: 100 },
    { field: "bronze", width: 100 },
    { field: "total", width: 100 },
  ],
};

function fillLarge() {
  setWidthAndHeight("100%");
}

function fillMedium() {
  setWidthAndHeight("60%");
}

function fillExact() {
  setWidthAndHeight("400px");
}

function setWidthAndHeight(size: string) {
  const eGridDiv = document.querySelector<HTMLElement>("#myGrid")! as any;
  eGridDiv.style.setProperty("width", size);
  eGridDiv.style.setProperty("height", size);
}

const gridDiv = document.querySelector<HTMLElement>("#myGrid")!;
gridApi = createGrid(gridDiv, gridOptions);

fetch("https://www.ag-grid.com/example-assets/olympic-winners.json")
  .then((response) => response.json())
  .then((data: IOlympicData[]) => gridApi!.setGridOption("rowData", data));

if (typeof window !== "undefined") {
  // Attach external event handlers to window so they can be called from index.html
  (<any>window).fillLarge = fillLarge;
  (<any>window).fillMedium = fillMedium;
  (<any>window).fillExact = fillExact;
}
```

[Live example: Width & Height](https://www.ag-grid.com/archive/36.2.0/examples/grid-size/width-and-height/typescript/)

### Dynamic Resizing without Horizontal Scroll

Sometimes you want to have columns that don't fit in the current viewport to simply be hidden altogether with no horizontal scrollbar.

To achieve this determine the width of the grid and work out how many columns could fit in that space, hiding any that don't fit, constantly updating based on the `gridSizeChanged` event firing, like the next example shows.

This example is best seen when opened in a new tab - then change the horizontal size of the browser and watch as columns hide/show based on the current grid size.

#### Dynamic horizontal resizing without scroll

```ts
import {
  ClientSideRowModelModule,
  ColumnApiModule,
  ColumnAutoSizeModule,
  FirstDataRenderedEvent,
  GridApi,
  GridOptions,
  GridSizeChangedEvent,
  ModuleRegistry,
  createGrid,
  enableDevValidations,
} from "ag-grid-community";
import { IOlympicData } from "./interfaces";

if (process.env.NODE_ENV !== "production") {
  // Enable extended validations only for development
  enableDevValidations();
}

ModuleRegistry.registerModules([
  ColumnAutoSizeModule,
  ColumnApiModule,
  ClientSideRowModelModule,
]);

let gridApi: GridApi<IOlympicData>;
let sizeToFitTimer: number | undefined;

const gridOptions: GridOptions<IOlympicData> = {
  columnDefs: [
    { field: "athlete", minWidth: 150 },
    { field: "age", minWidth: 70, maxWidth: 90 },
    { field: "country", minWidth: 130 },
    { field: "year", minWidth: 70, maxWidth: 90 },
    { field: "date", minWidth: 120 },
    { field: "sport", minWidth: 120 },
    { field: "gold", minWidth: 80 },
    { field: "silver", minWidth: 80 },
    { field: "bronze", minWidth: 80 },
    { field: "total", minWidth: 80 },
  ],
  onGridSizeChanged: onGridSizeChanged,
  onFirstDataRendered: onFirstDataRendered,
};

function onGridSizeChanged(params: GridSizeChangedEvent) {
  // get the current grids width
  const gridWidth = document.querySelector(".ag-grid-viewport")!.clientWidth;

  // keep track of which columns to hide/show
  const columnsToShow = [];
  const columnsToHide = [];

  // iterate over all columns (visible or not) in their current displayed order,
  // so that hiding follows the order the user sees rather than the column definition order
  let totalColsWidth = 0;
  const allColumns = params.api.getAllGridColumns();
  for (let i = 0, len = allColumns.length; i < len; i++) {
    const column = allColumns[i];
    totalColsWidth += column.getMinWidth();
    if (totalColsWidth > gridWidth) {
      columnsToHide.push(column.getColId());
    } else {
      columnsToShow.push(column.getColId());
    }
  }

  // show/hide columns based on current grid width
  params.api.setColumnsVisible(columnsToShow, true);
  params.api.setColumnsVisible(columnsToHide, false);

  // wait until columns stopped moving and fill out
  // any available space to ensure there are no gaps. The timer is cleared on every size change so
  // only the latest one re-fits, and the grid can be destroyed before it fires - hence the guard.
  window.clearTimeout(sizeToFitTimer);
  sizeToFitTimer = window.setTimeout(() => {
    if (params.api.isDestroyed()) {
      return;
    }
    params.api.sizeColumnsToFit();
  }, 10);
}

function onFirstDataRendered(params: FirstDataRenderedEvent) {
  params.api.sizeColumnsToFit();
}

const gridDiv = document.querySelector<HTMLElement>("#myGrid")!;
gridApi = createGrid(gridDiv, gridOptions);

fetch("https://www.ag-grid.com/example-assets/olympic-winners.json")
  .then((response) => response.json())
  .then((data: IOlympicData[]) => gridApi!.setGridOption("rowData", data));
```

[Live example: Dynamic horizontal resizing without scroll](https://www.ag-grid.com/archive/36.2.0/examples/grid-size/example1/typescript/)

### Dynamic Vertical Resizing

Sometimes the grid is taller than the rows it contains. You can dynamically set the row heights to fill the available height as the following example shows:

#### Dynamic vertical resizing

```ts
import {
  ClientSideRowModelApiModule,
  ClientSideRowModelModule,
  FirstDataRenderedEvent,
  GridApi,
  GridOptions,
  GridReadyEvent,
  GridSizeChangedEvent,
  ModuleRegistry,
  RenderApiModule,
  RowApiModule,
  RowHeightParams,
  createGrid,
  enableDevValidations,
} from "ag-grid-community";
import { getData } from "./data";

if (process.env.NODE_ENV !== "production") {
  // Enable extended validations only for development
  enableDevValidations();
}

ModuleRegistry.registerModules([
  ClientSideRowModelApiModule,
  RenderApiModule,
  RowApiModule,
  ClientSideRowModelModule,
]);

let minRowHeight = 25;
let currentRowHeight: number;

let gridApi: GridApi;

const gridOptions: GridOptions = {
  columnDefs: [
    { field: "athlete", width: 140 },
    { field: "age", width: 60 },
    { field: "country", width: 130 },
    { field: "year", width: 70 },
    { field: "date", width: 110 },
    { field: "sport", width: 110 },
    { field: "gold", flex: 1 },
    { field: "silver", flex: 1 },
    { field: "bronze", flex: 1 },
    { field: "total", flex: 1 },
  ],

  rowData: getData(),
  onGridReady: (params: GridReadyEvent) => {
    minRowHeight = params.api.getSizesForCurrentTheme().rowHeight;
    currentRowHeight = minRowHeight;
  },
  onFirstDataRendered: onFirstDataRendered,
  onGridSizeChanged: onGridSizeChanged,
  getRowHeight: (params: RowHeightParams) => {
    return currentRowHeight;
  },
};

function onFirstDataRendered(params: FirstDataRenderedEvent) {
  updateRowHeight(params);
}

function onGridSizeChanged(params: GridSizeChangedEvent) {
  updateRowHeight(params);
}

const updateRowHeight = (params: { api: GridApi }) => {
  // get the height of the grid body - this excludes the height of the headers
  const gridViewport = document.querySelector<HTMLElement>(".ag-grid-viewport");
  const topRows = document.querySelector<HTMLElement>(
    ".ag-grid-pinned-top-rows",
  );
  const bottomRows = document.querySelector<HTMLElement>(
    ".ag-grid-pinned-bottom-rows",
  );

  if (!gridViewport) {
    return;
  }

  const gridHeight =
    gridViewport.clientHeight -
    (topRows?.clientHeight ?? 0) -
    (bottomRows?.clientHeight ?? 0);
  // get the rendered rows
  const renderedRowCount = params.api.getDisplayedRowCount();
  if (renderedRowCount === 0) {
    return;
  }

  // if the rendered rows * min height is greater than available height, just set the height
  // to the min and let the scrollbar do its thing
  if (renderedRowCount * minRowHeight >= gridHeight) {
    if (currentRowHeight !== minRowHeight) {
      currentRowHeight = minRowHeight;
      params.api.resetRowHeights();
    }
  } else {
    // set the height of the row to the grid height / number of rows available
    currentRowHeight = Math.floor(gridHeight / renderedRowCount);
    params.api.resetRowHeights();
  }
};

const gridDiv = document.querySelector<HTMLElement>("#myGrid")!;
gridApi = createGrid(gridDiv, gridOptions);
```

[Live example: Dynamic vertical resizing](https://www.ag-grid.com/archive/36.2.0/examples/grid-size/example2/typescript/)

## Auto Height Layout

Depending on your scenario, you may wish for the grid to auto-size it's height to the number of rows displayed inside the grid. This is useful if you have relatively few rows and don't want empty space between the last row and the bottom of the grid.

To allow the grid to auto-size its height to fit rows, set grid property `domLayout='autoHeight'`.

When `domLayout='autoHeight'` then your application **should not** set height on the grid div, as the div should be allowed flow naturally to fit the grid contents. When auto height is off then your application **should** set height on the grid div, as the grid will fill the div you provide it.

> **Warning**
>
> There is no default maximum height, which means that the grid will render all rows. When using the Server-Side Row Model, this will mean loading the entire data set. For large grids (eg >1,000 rows) the draw time of the grid will be slow, or for very large grids, your application can freeze. This is not a problem with the grid, it is a limitation on browsers on how much data they can easily display on one web page. For this reason, if showing large amounts of data, set a [max height](https://www.ag-grid.com/archive/36.2.0/javascript-data-grid/grid-size/#minimum-and-maximum-height-with-auto-height) to limit the number of rows rendered.

The example below demonstrates the autoHeight feature. Notice the following:

- As you set different numbers of rows into the grid, the grid will resize its height to just fit the rows.
- As the grid height exceeds the height of the browser, you will need to use the browser vertical scroll to view data (or the iFrames scroll if you are looking at the example embedded below).
- The height will also adjust as you filter, to add and remove rows.
- If you have pinned rows, the grid will size to accommodate the pinned rows.
- Vertical scrolling will not happen, however horizontal scrolling, including pinned columns, will work as normal.
- You can switch the grid into and out of auto-height mode by calling `api.setGridOption('domLayout', layout)` or by changing the bound `domLayout` property.

> **Note**
>
> The following example is best viewed in a new tab, so it is obvious that there are no scroll bars. When viewed inline below, the scroll bars shown are for the containing iframe, not the grid.

#### Auto Height

```ts
import {
  ClientSideRowModelModule,
  ColGroupDef,
  GridApi,
  GridOptions,
  ModuleRegistry,
  NumberFilterModule,
  PinnedRowModule,
  TextFilterModule,
  createGrid,
  enableDevValidations,
} from "ag-grid-community";
import {
  ColumnMenuModule,
  ColumnsToolPanelModule,
  ContextMenuModule,
  RowGroupingModule,
} from "ag-grid-enterprise";

if (process.env.NODE_ENV !== "production") {
  // Enable extended validations only for development
  enableDevValidations();
}

ModuleRegistry.registerModules([
  TextFilterModule,
  PinnedRowModule,
  ClientSideRowModelModule,
  ColumnsToolPanelModule,
  ColumnMenuModule,
  ContextMenuModule,
  RowGroupingModule,
  NumberFilterModule,
]);

const columnDefs: ColGroupDef[] = [
  {
    headerName: "Core",
    children: [
      { headerName: "ID", field: "id" },
      { field: "make" },
      { field: "price", filter: "agNumberColumnFilter" },
    ],
  },
  {
    headerName: "Extra",
    children: [
      { field: "val1", filter: "agNumberColumnFilter" },
      { field: "val2", filter: "agNumberColumnFilter" },
      { field: "val3", filter: "agNumberColumnFilter" },
      { field: "val4", filter: "agNumberColumnFilter" },
      { field: "val5", filter: "agNumberColumnFilter" },
      { field: "val6", filter: "agNumberColumnFilter" },
      { field: "val7", filter: "agNumberColumnFilter" },
      { field: "val8", filter: "agNumberColumnFilter" },
      { field: "val9", filter: "agNumberColumnFilter" },
      { field: "val10", filter: "agNumberColumnFilter" },
    ],
  },
];

let gridApi: GridApi;

const gridOptions: GridOptions = {
  columnDefs: columnDefs,
  defaultColDef: {
    enableRowGroup: true,
    enableValue: true,
    filter: true,
  },
  rowData: getData(5),
  domLayout: "autoHeight",
  onGridReady: (params) => {
    document.querySelector("#currentRowCount")!.textContent = "5";
  },
  popupParent: document.body,
};

function createRow(index: number) {
  const makes = ["Toyota", "Ford", "BMW", "Phantom", "Porsche"];

  return {
    id: "D" + (1000 + index),
    make: makes[Math.floor(window.agRandom() * makes.length)],
    price: Math.floor(window.agRandom() * 100000),
    val1: Math.floor(window.agRandom() * 1000),
    val2: Math.floor(window.agRandom() * 1000),
    val3: Math.floor(window.agRandom() * 1000),
    val4: Math.floor(window.agRandom() * 1000),
    val5: Math.floor(window.agRandom() * 1000),
    val6: Math.floor(window.agRandom() * 1000),
    val7: Math.floor(window.agRandom() * 1000),
    val8: Math.floor(window.agRandom() * 1000),
    val9: Math.floor(window.agRandom() * 1000),
    val10: Math.floor(window.agRandom() * 1000),
  };
}

function getData(count: number) {
  const rowData = [];
  for (let i = 0; i < count; i++) {
    rowData.push(createRow(i));
  }
  return rowData;
}

function updateRowData(rowCount: number) {
  gridApi!.setGridOption("rowData", getData(rowCount));

  document.querySelector("#currentRowCount")!.textContent = `${rowCount}`;
}

function toggleFloatingRows() {
  const show = (document.getElementById("floating-rows") as HTMLInputElement)
    .checked;
  if (show) {
    gridApi!.setGridOption("pinnedTopRowData", [
      createRow(999),
      createRow(998),
    ]);
    gridApi!.setGridOption("pinnedBottomRowData", [
      createRow(997),
      createRow(996),
    ]);
  } else {
    gridApi!.setGridOption("pinnedTopRowData", undefined);
    gridApi!.setGridOption("pinnedBottomRowData", undefined);
  }
}

function setDomLayoutAutoHeight() {
  gridApi!.setGridOption("domLayout", "autoHeight");
  // auto height will get the grid to fill the height of the contents,
  // so the grid div should have no height set, the height is dynamic.
  (document.querySelector<HTMLElement>("#myGrid")! as any).style.height = "";
}

function setDomLayoutNormal() {
  gridApi!.setGridOption("domLayout", "normal");
  // when auto height is off, the grid has a fixed height and provides
  // scrollbars if the data does not fit into it.
  (document.querySelector<HTMLElement>("#myGrid")! as any)!.style.height =
    "400px";
}

const gridDiv = document.querySelector<HTMLElement>("#myGrid")!;
gridApi = createGrid(gridDiv, gridOptions);

if (typeof window !== "undefined") {
  // Attach external event handlers to window so they can be called from index.html
  (<any>window).updateRowData = updateRowData;
  (<any>window).toggleFloatingRows = toggleFloatingRows;
  (<any>window).setDomLayoutAutoHeight = setDomLayoutAutoHeight;
  (<any>window).setDomLayoutNormal = setDomLayoutNormal;
}
```

[Live example: Auto Height](https://www.ag-grid.com/archive/36.2.0/examples/grid-size/auto-height/typescript/)

### Minimum and Maximum Height with Auto Height

You can constrain the height of the grid body - the scrolling rows, excluding headers and pinned rows. By default the minimum height is 150px (because a zero-height grid looks weird) and there is no maximum height. This can be customised using two [theme parameters](https://www.ag-grid.com/archive/36.2.0/javascript-data-grid/theming-parameters/):

```js
const myTheme = themeQuartz.withParams({
    autoHeightMinBodyHeight: 0,
    autoHeightMaxBodyHeight: 400,
});
```

Once the height of the available rows exceeds the maximum height, the grid stops growing and scrolls instead, using [virtualisation](https://www.ag-grid.com/archive/36.2.0/javascript-data-grid/dom-virtualisation/) to ensure that large datasets are rendered efficiently.

You can see the effect of minimum and maximum heights with different numbers of rows in the following example:

#### Max Height with Auto Height

```ts
import {
  ClientSideRowModelModule,
  GridOptions,
  ModuleRegistry,
  createGrid,
  enableDevValidations,
  themeQuartz,
} from "ag-grid-community";

if (process.env.NODE_ENV !== "production") {
  // Enable extended validations only for development
  enableDevValidations();
}

ModuleRegistry.registerModules([ClientSideRowModelModule]);

let rowCount = 5;
let minBodyHeight = 100;
let maxBodyHeight: number | "none" = 250;

function buildTheme() {
  return themeQuartz.withParams({
    autoHeightMinBodyHeight: minBodyHeight,
    autoHeightMaxBodyHeight: maxBodyHeight,
  });
}

const makes = ["Toyota", "Ford", "BMW", "Porsche", "Audi"];

function getData(count: number) {
  const rowData = [];
  for (let i = 0; i < count; i++) {
    rowData.push({
      id: "D" + (1000 + i),
      make: makes[i % makes.length],
      model: "Model " + (i + 1),
      price: 20000 + i * 750,
    });
  }
  return rowData;
}

const gridOptions: GridOptions = {
  theme: buildTheme(),
  domLayout: "autoHeight",
  columnDefs: [
    { field: "id" },
    { field: "make" },
    { field: "model" },
    { field: "price" },
  ],
  defaultColDef: {
    flex: 1,
  },
  rowData: getData(rowCount),
};

const gridApi = createGrid(
  document.querySelector<HTMLElement>("#myGrid")!,
  gridOptions,
);

function onRowCountChanged() {
  rowCount = Number(
    (document.getElementById("row-count") as HTMLInputElement).value,
  );
  gridApi.setGridOption("rowData", getData(rowCount));
}

function onMinBodyHeightChanged() {
  minBodyHeight = Number(
    (document.getElementById("min-body-height") as HTMLInputElement).value,
  );
  gridApi.setGridOption("theme", buildTheme());
}

function onMaxBodyHeightChanged() {
  const value = (document.getElementById("max-body-height") as HTMLInputElement)
    .value;
  // an empty control means no maximum, the default for auto height
  maxBodyHeight = value === "" ? "none" : Number(value);
  gridApi.setGridOption("theme", buildTheme());
}

if (typeof window !== "undefined") {
  // Attach external event handlers to window so they can be called from index.html
  (<any>window).onRowCountChanged = onRowCountChanged;
  (<any>window).onMinBodyHeightChanged = onMinBodyHeightChanged;
  (<any>window).onMaxBodyHeightChanged = onMaxBodyHeightChanged;
}
```

[Live example: Max Height with Auto Height](https://www.ag-grid.com/archive/36.2.0/examples/grid-size/auto-height-max/typescript/)

## Print Layout

For details on displaying the grid in a printer friendly layout see the [Print Layout](https://www.ag-grid.com/archive/36.2.0/javascript-data-grid/printing/) page.
