How to Test CSS Anchor Positioning, Popovers, and Overlay Stacking Without Chasing Layout Flakes
By Antoine Dubois · November 15, 2026
A practical guide to testing CSS anchor positioning, popovers, focus flow, and overlay stacking in browser automation, with stable assertions that avoid brittle pixel checks.
Modern floating UI is awkward to test for a simple reason, it is supposed to react to layout. Tooltips, menus, dialogs, and popovers can move when the viewport changes, when a scroll container clips them, when a new stacking context appears, or when the browser decides a feature is only partially supported. If your assertions focus on exact pixels, you will spend more time debugging the test than the UI.
The better approach is to test the contract, not the paint. For CSS anchor positioning and the Popover API, that means checking whether the element opens and closes correctly, whether it is attached to the expected anchor, whether it remains visible in the right stacking layer, and whether keyboard focus behaves as the platform expects. Use pixel checks sparingly, only for a small set of visual regressions that truly need them.
What needs to be true for floating UI to work
Three browser features are easy to confuse:
- CSS anchor positioning places an element relative to an anchor element using CSS, so the browser can resolve floating geometry without custom JavaScript math. See the CSS Anchor Positioning spec and related docs in the CSS Working Group draft and MDN.
- Popover API gives an element a built-in open and close state, with top-layer behavior for supported popovers. MDN documents this on the popover attribute.
- Overlay stacking is the visible result of stacking contexts, top layer placement,
z-index, transforms, opacity, containment, and portals. This is not a single API, it is the interaction of multiple browser rules.
If a test only checks “it appears somewhere,” it can pass while the menu is hidden behind a modal, clipped by a scroll container, or detached from the wrong trigger.
That is why the test strategy should be layered. Verify state first, then geometry constraints, then focus and dismissal behavior, then a narrow visual check only if the feature is especially sensitive.
The test dimensions that matter most
For component libraries and design systems, I would organize validation around these four dimensions.
| Dimension | What to assert | Why it matters |
|---|---|---|
| Open state | popover open, hidden, or toggled state |
Prevents false positives where the DOM exists but the UI is inactive |
| Anchor relationship | The floating element is anchored to the intended trigger | Catches regressions from renamed IDs, portal changes, or broken selectors |
| Stacking and clipping | Element is not hidden behind another layer, and is not clipped by a scroll container | Finds z-index and overflow regressions without exact screenshots |
| Interaction model | Focus moves correctly, Escape closes, click outside dismisses when expected | Confirms accessibility and browser-native behavior |
The key point is that these checks are observable from the DOM and accessibility tree. You do not need to infer correctness from a single screenshot.
A stable browser automation pattern
Playwright is a good fit here because it can inspect visibility, bounding boxes, focus, and keyboard behavior without forcing you into brittle sleeps. The same principles apply if you use Cypress or a Selenium-based stack, but the API examples below use Playwright because the assertions are compact and readable.
Start with a deterministic fixture
Use a small fixture page with one trigger, one floating panel, and one scroll container. Avoid real application chrome until the rule is stable.
```html
<button id="trigger" popovertarget="menu">Open menu</button>
That example is intentionally simple. The exact CSS for anchor positioning depends on the feature subset you are using, but the test value comes from keeping the DOM minimal. A minimal fixture makes it much easier to tell whether a failure is caused by the feature under test or by surrounding layout.
## Assert state first, geometry second
The first assertion should answer a basic question, is the overlay actually open?
```typescript
import { test, expect } from '@playwright/test';
test('popover opens and closes', async ({ page }) => {
await page.goto('/floating-fixture.html');
await page.getByRole('button', { name: 'Open menu' }).click();
const menu = page.locator('#menu');
await expect(menu).toBeVisible();
await page.keyboard.press('Escape');
await expect(menu).not.toBeVisible();
});
This catches the basic open and close contract and avoids hard-coding animation timing. If your implementation uses transitions, prefer waiting on the state that actually matters, for example toBeVisible() or a CSS class that represents the open state, rather than waitForTimeout().
After that, check geometry in a way that tolerates browser differences. For anchor positioning, avoid exact coordinates. Compare relative placement and sanity bounds instead.
const trigger = page.locator('#trigger');
const menu = page.locator('#menu');
const triggerBox = await trigger.boundingBox();
const menuBox = await menu.boundingBox();
expect(triggerBox).not.toBeNull(); expect(menuBox).not.toBeNull(); expect(menuBox!.y).toBeGreaterThanOrEqual(triggerBox!.y);
This example is deliberately loose. You are not proving the element is pixel-perfect, you are proving it landed in a plausible place. That is enough for most regression tests.
Test anchor positioning as a relationship, not a coordinate map
When you test CSS anchor positioning in browser automation, the common failure is over-specification. The browser may flip placement, shift the overlay to avoid clipping, or round subpixel geometry differently across engines. Those are not always defects.
A better pattern is to check a few invariants:
- The anchor exists and is the one the overlay references.
- The overlay is rendered in the expected axis relative to that anchor for the chosen viewport size.
- The overlay remains within the viewport or within the intended clipping region.
- Any fallback placement still keeps the overlay usable.
Here is a practical viewport-based check:
await page.setViewportSize({ width: 1024, height: 768 });
await page.getByRole('button', { name: 'Open menu' }).click();
const box = await page.locator('#menu').boundingBox();
expect(box).not.toBeNull();
expect(box!.x).toBeGreaterThanOrEqual(0);
expect(box!.y).toBeGreaterThanOrEqual(0);
expect(box!.x + box!.width).toBeLessThanOrEqual(1024);
expect(box!.y + box!.height).toBeLessThanOrEqual(768);
If your design intentionally allows overflow, change the invariant. The important part is that the test encodes the product decision, not an accidental assumption about layout.
Stacking context bugs are usually not z-index bugs alone
Overlay layering issues often get mislabeled as z-index regressions. In reality, the failure is often caused by a new stacking context created by transform, filter, opacity < 1, position plus z-index, contain, or a portal boundary.
Testing should reflect that.
A useful assertion is overlap, not just existence
If the overlay is supposed to sit above a neighboring card, verify that it can actually receive pointer events and is not visually covered by another element at the point of interaction. You can do this by checking the topmost element at a coordinate inside the overlay.
const menu = page.locator('#menu');
const box = await menu.boundingBox();
expect(box).not.toBeNull();
const topElement = await page.evaluate(({ x, y }) => {
const el = document.elementFromPoint(x, y);
return el?.id || el?.tagName || null;
}, { x: box!.x + 10, y: box!.y + 10 });
expect(topElement).toBe(‘menu’);
This is more meaningful than a screenshot comparison when the problem is stacking order. If elementFromPoint returns the wrong element, the overlay may be behind another layer even if it is present in the DOM.
Watch for scroll container clipping
A menu can be correctly positioned and still be unusable if a parent container hides it with overflow: hidden or overflow: auto. Add one fixture where the trigger sits near the bottom of a clipped container, then assert that the overlay is either moved into a safe layer or remains visible.
If your component uses portals, this is the place where a regression often appears. The portal may solve clipping while introducing a new focus or stacking issue, so test both behavior and visibility.
Focus management is part of the feature
A floating UI element is not correct if keyboard users cannot move through it predictably. For popover testing, validate the focus path and dismissal path together.
Recommended checks:
- Trigger receives focus before opening.
- Opening the popover moves focus only if the design requires it.
- Tab key moves through menu items in the intended order.
- Escape closes the overlay and returns focus where the spec or your component contract says it should.
- Clicking outside closes the overlay only when that behavior is expected.
await page.getByRole('button', { name: 'Open menu' }).focus();
await page.keyboard.press('Enter');
await expect(page.locator('#menu')).toBeVisible();
await page.keyboard.press('Tab');
const active = await page.evaluate(() => document.activeElement?.textContent);
expect(active).toContain('First action');
Do not assume all browsers will treat native popovers and custom overlays identically. The browser can manage top-layer behavior for the popover attribute, while your app code may still need to manage menu semantics, roving tabindex, and return focus. Treat those as separate responsibilities.
Reduce flakiness by testing at multiple viewport sizes
A single desktop viewport is not enough for floating UI. Placement bugs often appear only when the trigger is near the right edge, bottom edge, or inside a narrow container.
A practical matrix is small but deliberate:
- one wide viewport,
- one narrow viewport,
- one viewport where the trigger is near the bottom edge,
- one viewport where the trigger is inside a scrollable region.
You do not need a screenshot for every combination. A few placement and visibility assertions usually catch the regression class you care about.
If you want a visual test, limit it to the final rendered state and use it as a smoke check, not as the only proof. A single screenshot can tell you that something changed, but not whether the change broke the contract.
Where pixel checks still make sense
There are cases where screenshots are still useful:
- the UI uses carefully tuned arrow placement,
- a design system promises exact spacing around the trigger,
- the overlay uses CSS effects that are hard to model with DOM assertions alone,
- a browser update changed font metrics or line wrapping in a visible way.
Even then, keep the visual test narrow. Capture the floating component in isolation, at a known viewport, with a stable data fixture. Do not capture the whole application shell unless that shell is part of the behavior under test.
A debugging checklist that saves time
When a floating UI test fails, the failure usually falls into one of five buckets:
- The overlay never opened, inspect the trigger event, popover state, and any disabled logic.
- The overlay opened but is invisible, check
display,visibility,opacity, and clipping ancestors. - The overlay is visible but misplaced, inspect anchor references, viewport size, and fallback placement.
- The overlay is behind something else, inspect stacking contexts, portals, and
elementFromPointat the interaction point. - Keyboard behavior is wrong, inspect focus order, escape handling, and ARIA roles.
If you want a fast isolation step, remove animation and transitions from the fixture. Many flakes vanish once timing is out of the equation, which tells you the real bug is either a race or a bad wait condition.
A simple decision rule
Use DOM and accessibility assertions for most tests. Use geometry assertions when placement matters. Use a screenshot only when the visual relationship itself is the product requirement.
That rule scales well for component libraries, because it keeps tests tied to behavior rather than render noise. It also makes failures easier to interpret during code review, which matters when overlay bugs are fixed by both design and engineering.
FAQ
Is CSS anchor positioning safe to test without screenshots?
Yes, if the contract is relational rather than pixel-perfect. Check visibility, relative placement, viewport bounds, and fallback behavior. Use screenshots only for narrow visual requirements.
How do I test popover open and close states reliably?
Trigger the interaction, assert visibility, then close with Escape, outside click, or the component’s documented close path. Avoid fixed delays unless the UI has an intentional animation contract.
What causes overlay stacking regressions most often?
New stacking contexts, portal changes, scroll container clipping, and unintentional z-index conflicts. A test that uses elementFromPoint can catch many of these without a full visual diff.
Should floating UI tests run only in one browser?
No. Placement and stacking can differ across engines. At minimum, cover the browsers your users actually rely on, especially if you use native popovers or emerging CSS features.
When is a visual regression test worth keeping?
Keep it when spacing, arrows, or visual alignment are part of the feature contract and DOM assertions cannot express the requirement cleanly.
What is the most important thing to avoid?
Brittle exact-pixel assertions on a feature that is designed to adapt to layout. Those tests are usually the first ones to fail for harmless reasons and the last ones to explain the real bug.