---
title: "Floating UI"
description: "Use the rectangle the grid computes as a Floating UI virtual element, so a floating element follows items that are not rendered."
canonical_url: "https://vvirtual-grid.netlify.app/guides/floating-ui"
---
# Floating UI

> Use the rectangle the grid computes as a Floating UI virtual element, so a floating element follows items that are not rendered.

In this guide you position a floating element next to a grid item with [Floating UI](https://floating-ui.com), including flipping and shifting when the item is near the edge of the scroll container. Floating UI is a library that positions one element next to another.

Floating UI measures its reference element with `getBoundingClientRect()`. A virtual item that scrolled out of the grid has no element to measure. Floating UI accepts a plain object with a `getBoundingClientRect()` method, called a virtual element. You give it the rectangle the grid computes for the index, so the floating element keeps working when the item is not in the DOM.

<floating-demo>



</floating-demo>

In the demo, the popover keeps following the clicked item after you scroll far enough that the item is no longer in the DOM.

## Build the virtual element

The rectangle comes from `getItemRect`. Set `root` to the grid element, so the rectangle holds viewport coordinates, as `getBoundingClientRect()` does. The [`rect`](https://vvirtual-grid.netlify.app/reference/primitives#query-objects) field has the fields of a `DOMRect`, so Floating UI can read it as the reference rectangle.

<steps level="3">

### Create the query and the virtual element

Create the query once. The virtual element updates the query, calls `getItemRect`, and returns `query.rect`. Reusing one query object avoids a new rectangle on every scroll event. Put the virtual element in a `shallowRef`. The object never changes, so it does not need deep reactivity.

The grid uses the scroll container, column tracks and probe from [Sizing and direction](https://vvirtual-grid.netlify.app/guides/sizing-and-direction).

```vue
<script setup>
import { ref, shallowRef, useTemplateRef } from "vue";
import { createPageProvider } from "vvirtual-grid/vue";
import { createRectQuery, getItemRect } from "vvirtual-grid/primitives";

const items = Array.from({ length: 10000 }, (_, i) => ({ title: `Item ${i + 1}` }));
const pageProvider = createPageProvider(items);
const grid = useTemplateRef("grid");
const anchored = ref(-1);
const query = createRectQuery();

const reference = shallowRef({
  getBoundingClientRect() {
    query.root = grid.value.$el;
    query.index = anchored.value;
    query.layout = grid.value.measurement;
    getItemRect(query);
    return query.rect;
  },
});
</script>
```

Render the grid, and set `anchored` to the index of the item the user clicks.

```vue
<template>
  <div class="h-96 overflow-y-auto">
    <VirtualGrid
      ref="grid"
      :length="items.length"
      :page-size="40"
      :page-provider="pageProvider"
    >
      <template #default="{ item, index, style }">
        <button :style="style" :data-index="index" @click="anchored = index">
          {{ item.title }}
        </button>
      </template>
    </VirtualGrid>
  </div>
</template>
```

If `getItemRect` returns `false`, `query.rect` keeps its last values. The floating element then stays where it was until the next call succeeds.

### Position with `useFloating`

With `@floating-ui/vue`, pass the virtual element, the floating element and the options to `useFloating`. Use `strategy: "fixed"`, because the rectangle holds viewport coordinates.

```vue
<script setup>
import { useFloating, offset, flip, shift } from "@floating-ui/vue";

const floating = useTemplateRef("floating");

const { floatingStyles, update } = useFloating(reference, floating, {
  strategy: "fixed",
  placement: "bottom-start",
  middleware: [offset(4), flip(), shift()],
});
</script>

<template>
  <div ref="floating" popover :style="floatingStyles" style="margin: 0; inset: auto">
    Item {{ anchored }}
  </div>
</template>
```

`floatingStyles` sets `position`, `left`, `top` and `transform` on the element. The inline `margin` and `inset` reset what the browser sets on a native `popover`. The `popover` attribute also keeps the floating element in the top layer, so the scroll container does not clip it.

### Update on scroll and layout changes

`useFloating` computes the position when the elements change. It does not know that the grid scrolled or that the item size changed. Call `update()` from the grid's events.

```vue
<template>
  <div class="h-96 overflow-y-auto">
    <VirtualGrid
      ref="grid"
      :length="items.length"
      :page-size="40"
      :page-provider="pageProvider"
      @viewport-scroll="update"
      @layout-change="update"
      class="grid grid-cols-[repeat(auto-fill,minmax(120px,1fr))] gap-2"
    >
      <!-- the default, placeholder and probe slots -->
    </VirtualGrid>
  </div>
</template>
```

Also call `update()` right after you change `anchored`, because the index changed but no element did. Show the popover before you call `update()`. A hidden popover has no size, and Floating UI only treats it as shown in the top layer after `showPopover()`. Replace `@click="anchored = index"` from [Create the query and the virtual element](#create-the-query-and-the-virtual-element) with `@click="open(index)"`:

```ts
function open(index) {
  anchored.value = index;
  floating.value.showPopover();
  update();
}
```

### Flip at the edge of the scroll container

By default, `flip()` and `shift()` keep the floating element inside the browser window. A popover sits in the top layer, so the scroll container does not clip it, and Floating UI does not count the container as an edge. To flip at the container's edge instead, pass the container as `boundary` to both. Add `ref="scroller"` to the scroll container.

```ts
import { onMounted } from "vue";

const scroller = useTemplateRef("scroller");
const overflow: { boundary?: Element } = {};

onMounted(() => {
  overflow.boundary = scroller.value ?? undefined;
});
```

Then change the `middleware` option from [Position with `useFloating`](#position-with-usefloating) to `[offset(4), flip(overflow), shift(overflow)]`. Floating UI reads `overflow.boundary` on every update, so one object serves both and no update creates a new one.

### Check that it follows the item

Open the floating element on an item, then scroll far enough that the item leaves the DOM. The element keeps moving with the item's position. To confirm the item left the DOM, open the Elements panel and expand the grid. It has no child with the item's `data-index`.

Open it on an item near the bottom edge of the scroll container. `flip()` moves it above the item.

</steps>

## Use `autoUpdate`

`useFloating` can call `update()` for you through `whileElementsMounted`.

```ts
import { autoUpdate } from "@floating-ui/vue";

useFloating(reference, floating, {
  strategy: "fixed",
  middleware: [offset(4), flip(), shift()],
  whileElementsMounted: autoUpdate,
});
```

`autoUpdate` watches the reference element's scroll parents. A virtual element has no element, so `autoUpdate` cannot watch the grid's scroll container through the reference. Keep the `@viewport-scroll="update"` and `@layout-change="update"` handlers from [Update on scroll and layout changes](#update-on-scroll-and-layout-changes). `autoUpdate` also cannot see a change of item size or gap.

## Use `@floating-ui/dom` without Vue

`computePosition` takes the same virtual element and returns the coordinates. Pass it `reference.value` and `floating.value`, the virtual element and the floating element from [Create the query and the virtual element](#create-the-query-and-the-virtual-element) and [Position with `useFloating`](#position-with-usefloating), and write the coordinates to the element yourself.

```ts
import { computePosition, offset, flip, shift } from "@floating-ui/dom";

async function place() {
  const { x, y } = await computePosition(reference.value, floating.value, {
    strategy: "fixed",
    placement: "bottom-start",
    middleware: [offset(4), flip(), shift()],
  });
  floating.value.style.translate = `${x}px ${y}px`;
}
```

The element needs this CSS, so the translation starts at the top left of the window. A native `popover` has `margin: auto` by default, which centers it.

```css
[popover] {
  position: fixed;
  inset: 0 auto auto 0;
  margin: 0;
}
```

Call `place()` on `viewport-scroll` and `layout-change`, as in [Update on scroll and layout changes](#update-on-scroll-and-layout-changes), and once right after `showPopover()`.


## Sitemap

See the full [sitemap](https://vvirtual-grid.netlify.app/sitemap.md) for all pages.
