---
title: "Grid Layout"
framework: vue
version: "36.1.0"
---

# Grid Layout

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

```html
<!-- set width using percentages -->
<ag-grid-vue style="width: 100%; height: 100%;"></ag-grid-vue>

<!-- OR set width using fixed pixels -->
<ag-grid-vue style="width: 500px; height: 200px"></ag-grid-vue>
```

> **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 is set to fit the number of rows so no vertical scrollbar is provided by the grid. The grid scrolls horizontally as normal. Note that if using this with the SSRM the grid will attempt to load every row and may cause undesired side-effects (such as excessive datasource requests or too many loaded rows).
- **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/vue-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 { createApp } from "vue";

import type { ColDef, GridReadyEvent } from "ag-grid-community";
import {
  ClientSideRowModelModule,
  ModuleRegistry,
  enableDevValidations,
} from "ag-grid-community";
import { AgGridVue } from "ag-grid-vue3";

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

ModuleRegistry.registerModules([ClientSideRowModelModule]);

const VueExample = {
  template: `
        <div style="display: flex; flex-direction: column; height: 100%">
            <div style="margin-bottom: 5px;">
                <button @click="fillLarge">Fill 100%</button>
                <button @click="fillMedium">Fill 60%</button>
                <button @click="fillExact">Exactly 400 x 400 pixels</button>
            </div>
            <div style="width: 100%; flex: 1 1 auto;">
                <ag-grid-vue :style="{width, height}"
                             @grid-ready="onGridReady"
                             :columnDefs="columnDefs"
                             :rowData="rowData"
                             ></ag-grid-vue>
            </div>
        </div>
    `,
  components: {
    "ag-grid-vue": AgGridVue,
  },
  data: function () {
    return {
      columnDefs: null,
      rowData: null,
      height: "100%",
      width: "100%",
    };
  },
  beforeMount() {
    this.columnDefs = <ColDef[]>[
      { 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 },
    ];
  },
  methods: {
    fillLarge() {
      this.setWidthAndHeight("100%", "100%");
    },
    fillMedium() {
      this.setWidthAndHeight("60%", "60%");
    },
    fillExact() {
      this.setWidthAndHeight("400px", "400px");
    },
    setWidthAndHeight(width, height) {
      this.width = width;
      this.height = height;
    },
    onGridReady(params: GridReadyEvent) {
      const updateData = (data) => (this.rowData = data);

      fetch("https://www.ag-grid.com/example-assets/olympic-winners.json")
        .then((resp) => resp.json())
        .then((data) => updateData(data));
    },
  },
};

createApp(VueExample).mount("#app");
```

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

### 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 {
  createApp,
  defineComponent,
  onBeforeMount,
  ref,
  shallowRef,
} from "vue";
import { AgGridVue } from "ag-grid-vue3";
import {
  ClientSideRowModelModule,
  ColDef,
  ColGroupDef,
  ColumnApiModule,
  ColumnAutoSizeModule,
  FirstDataRenderedEvent,
  GridApi,
  GridOptions,
  GridReadyEvent,
  GridSizeChangedEvent,
  ModuleRegistry,
  enableDevValidations,
} from "ag-grid-community";
import { IOlympicData } from "./interfaces";
if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

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

const VueExample = defineComponent({
  template: `
        <div style="height: 100%">
                <div id="grid-wrapper" style="width: 100%; height: 100%">
      <ag-grid-vue
        style="width: 100%; height: 100%;"
        @grid-ready="onGridReady"
        :columnDefs="columnDefs"
        :rowData="rowData"
        @grid-size-changed="onGridSizeChanged"
        @first-data-rendered="onFirstDataRendered"></ag-grid-vue>
      </div>
        </div>
    `,
  components: {
    "ag-grid-vue": AgGridVue,
  },
  setup(props) {
    const gridApi = shallowRef<GridApi<IOlympicData> | null>(null);
    const columnDefs = ref<ColDef[]>([
      { 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 },
    ]);
    const rowData = ref<IOlympicData[]>(null);

    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
      window.setTimeout(() => {
        params.api.sizeColumnsToFit();
      }, 10);
    }
    function onFirstDataRendered(params: FirstDataRenderedEvent) {
      params.api.sizeColumnsToFit();
    }
    const onGridReady = (params: GridReadyEvent) => {
      gridApi.value = params.api;

      const updateData = (data) => (rowData.value = data);

      fetch("https://www.ag-grid.com/example-assets/olympic-winners.json")
        .then((resp) => resp.json())
        .then((data) => updateData(data));
    };

    return {
      gridApi,
      columnDefs,
      rowData,
      onGridReady,
      onGridSizeChanged,
      onFirstDataRendered,
    };
  },
});

const app = createApp(VueExample);
app.mount("#app");
```

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

### 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 {
  createApp,
  defineComponent,
  onBeforeMount,
  ref,
  shallowRef,
} from "vue";
import { AgGridVue } from "ag-grid-vue3";
import {
  ClientSideRowModelApiModule,
  ClientSideRowModelModule,
  ColDef,
  ColGroupDef,
  FirstDataRenderedEvent,
  GetRowHeight,
  GridApi,
  GridOptions,
  GridReadyEvent,
  GridSizeChangedEvent,
  ModuleRegistry,
  RenderApiModule,
  RowApiModule,
  RowHeightParams,
  enableDevValidations,
} from "ag-grid-community";
import { getData } from "./data";
if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

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

let minRowHeight = 25;

let currentRowHeight: number;

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 VueExample = defineComponent({
  template: `
        <div style="height: 100%">
                <ag-grid-vue
      style="width: 100%; height: 100%;"
      @grid-ready="onGridReady"
      :columnDefs="columnDefs"
      :rowData="rowData"
      :getRowHeight="getRowHeight"
      @first-data-rendered="onFirstDataRendered"
      @grid-size-changed="onGridSizeChanged"></ag-grid-vue>
        </div>
    `,
  components: {
    "ag-grid-vue": AgGridVue,
  },
  setup(props) {
    const gridApi = shallowRef<GridApi | null>(null);
    const columnDefs = ref<ColDef[]>([
      { 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 },
    ]);
    const rowData = ref<any[] | null>(getData());
    const getRowHeight = ref<GetRowHeight>((params: RowHeightParams) => {
      return currentRowHeight;
    });

    function onFirstDataRendered(params: FirstDataRenderedEvent) {
      updateRowHeight(params);
    }
    function onGridSizeChanged(params: GridSizeChangedEvent) {
      updateRowHeight(params);
    }
    const onGridReady = (params: GridReadyEvent) => {
      gridApi.value = params.api;

      minRowHeight = params.api.getSizesForCurrentTheme().rowHeight;
      currentRowHeight = minRowHeight;
    };

    return {
      gridApi,
      columnDefs,
      rowData,
      getRowHeight,
      onGridReady,
      onFirstDataRendered,
      onGridSizeChanged,
    };
  },
});

const app = createApp(VueExample);
app.mount("#app");
```

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

## 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**
>
> If using Grid Auto Height, then the grid will render all rows into the DOM. This is different to normal operation where the grid will only render rows that are visible inside the grid's scrollable viewport. 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, it is not advisable to use Grid Auto Height. Instead use the grid as normal and the grid's row virtualisation will take care of this problem for you.

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 {
  createApp,
  defineComponent,
  onBeforeMount,
  ref,
  shallowRef,
} from "vue";
import { AgGridVue } from "ag-grid-vue3";
import "./style.css";
import {
  ClientSideRowModelModule,
  ColDef,
  ColGroupDef,
  DomLayoutType,
  GridApi,
  GridOptions,
  GridReadyEvent,
  ModuleRegistry,
  NumberFilterModule,
  PinnedRowModule,
  TextFilterModule,
  enableDevValidations,
} from "ag-grid-community";
import {
  ColumnMenuModule,
  ColumnsToolPanelModule,
  ContextMenuModule,
  RowGroupingModule,
} from "ag-grid-enterprise";
if (process.env.NODE_ENV !== "production") {
  enableDevValidations();
}

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

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;
}

const VueExample = defineComponent({
  template: `
        <div style="height: 100%">
                <div class="test-header">
      <div>
        <button v-on:click="updateRowData(0)">0 Rows</button>
        <button v-on:click="updateRowData(5)">5 Rows</button>
        <button v-on:click="updateRowData(50)">50 Rows</button>
      </div>
      <div>
        <button v-on:click="setDomLayoutAutoHeight()">Auto Height</button>
        <button v-on:click="setDomLayoutNormal()">Fixed Height</button>
      </div>
      <div>
        <input name="pinned-rows" type="checkbox" id="floating-rows" v-on:click="toggleFloatingRows()">
          <label for="pinned-rows"> Pinned Rows </label>
        </div>
        <div>Row Count = <span id="currentRowCount"></span></div>
      </div>
      <ag-grid-vue
        id="myGrid"
        @grid-ready="onGridReady"
        :columnDefs="columnDefs"
        :defaultColDef="defaultColDef"
        :rowData="rowData"
        :domLayout="domLayout"
        :popupParent="popupParent"></ag-grid-vue>
        <div style="border: 10px solid #eee; padding: 10px; margin-top: 20px">
          <p style="text-align: center">
            This text is under the grid and should move up and down as the height of the grid changes.
          </p>
        </div>
        </div>
    `,
  components: {
    "ag-grid-vue": AgGridVue,
  },
  setup(props) {
    const gridApi = shallowRef<GridApi | null>(null);
    const columnDefs = ref<(ColDef | 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" },
        ],
      },
    ]);
    const defaultColDef = ref<ColDef>({
      enableRowGroup: true,
      enableValue: true,
      filter: true,
    });
    const rowData = ref<any[] | null>(getData(5));
    const domLayout = ref<DomLayoutType>("autoHeight");
    const popupParent = ref<HTMLElement | null>(document.body);

    function updateRowData(rowCount: number) {
      gridApi.value!.setGridOption("rowData", getData(rowCount));
      document.querySelector("#currentRowCount")!.textContent = `${rowCount}`;
    }
    function toggleFloatingRows() {
      const show = (
        document.getElementById("floating-rows") as HTMLInputElement
      ).checked;
      if (show) {
        gridApi.value!.setGridOption("pinnedTopRowData", [
          createRow(999),
          createRow(998),
        ]);
        gridApi.value!.setGridOption("pinnedBottomRowData", [
          createRow(997),
          createRow(996),
        ]);
      } else {
        gridApi.value!.setGridOption("pinnedTopRowData", undefined);
        gridApi.value!.setGridOption("pinnedBottomRowData", undefined);
      }
    }
    function setDomLayoutAutoHeight() {
      gridApi.value!.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.value!.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 onGridReady = (params: GridReadyEvent) => {
      gridApi.value = params.api;

      document.querySelector("#currentRowCount")!.textContent = "5";
    };

    return {
      gridApi,
      columnDefs,
      defaultColDef,
      rowData,
      domLayout,
      popupParent,
      onGridReady,
      updateRowData,
      toggleFloatingRows,
      setDomLayoutAutoHeight,
      setDomLayoutNormal,
    };
  },
});

const app = createApp(VueExample);
app.mount("#app");
```

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

### Min Height with Auto Height

When using Auto Height, the grid rows section has a minimum height of 150px. This is to avoid a zero-height grid which looks weird.

Use the `autoHeightMinBodyHeight` [theme parameter](https://www.ag-grid.com/vue-data-grid/theming-parameters/) to change this minimum:

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

It is not possible to specify a max height when using auto-height.

> **Note**
>
> Users ask is it possible to set a max height when using auto-height? The answer is no. If using auto-height, the grid is set up to work in a different way. It is not possible to switch. If you do need to switch, you will need to turn auto-height off.

## Print Layout

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