Sub topic 13
Positioning a popover next to its invoker
This chapter assumes you can already open a popover with popovertarget, you know what the top layer is, and you can read basic CSS. It covers why a popover does not appear beside its button by default, and how to place it there with CSS anchor positioning or with a JavaScript fallback.
Why the default position is the center of the viewport
A popover that opens next to its button looks natural, but the browser does not do this for you. The user agent stylesheet gives every [popover] element roughly these rules:
[popover] {
position: fixed;
inset: 0;
margin: auto;
width: fit-content;
height: fit-content;
}position: fixed with inset: 0 and margin: auto centers the box in the viewport. Because a popover lives in the top layer, its containing block is the viewport. It ignores the position of its ancestors. Placing the <div popover> right after the button in your markup has no effect on where it appears.
Two consequences follow:
- To move a popover you must change its inset values, and you must also neutralize the defaults. Setting only
topandleftleavesright: 0,bottom: 0, andmargin: autoin place. The box then stays centered or stretches in surprising ways. - Wrapping the button and popover in a
position: relativecontainer does not help. The container is not the popover's containing block.
Three ways to place a popover
| Approach | How it works | Tracks scrolling | Handles viewport edges | Browser support |
|---|---|---|---|---|
| CSS anchor positioning | The browser positions the popover relative to a named anchor element | Yes | Yes, with `position-try-fallbacks` | Newer browsers only. Check a current support table. |
| JavaScript measuring | Script reads `getBoundingClientRect()` and sets `top` and `left` | Only if you recompute | Only if you write the logic | Everywhere popover works |
| Fixed offsets | Hard-coded values such as `top: 4rem; right: 1rem` | Not applicable | No | Everywhere |
Fixed offsets suit things that do not relate to a single invoker, such as a toast pinned to a corner. The other two are for popovers that must sit beside a specific button.
CSS anchor positioning
Anchor positioning links two elements by name. You give the invoker an anchor-name, which must be a dashed identifier. You then tell the popover which anchor to use with position-anchor. Inside the popover's rules you can use the anchor() function to read an edge of the anchor.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Anchored menu</title>
<style>
#menu-button {
anchor-name: --menu-button;
}
#menu {
margin: 0;
inset: auto;
position-anchor: --menu-button;
top: anchor(bottom);
left: anchor(left);
padding: 0.5rem;
border: 1px solid #888;
border-radius: 8px;
}
</style>
</head>
<body>
<button id="menu-button" popovertarget="menu">Menu</button>
<div id="menu" popover>
<a href="/profile">Profile</a><br>
<a href="/settings">Settings</a>
</div>
</body>
</html>The popover's top edge lines up with the button's bottom edge, and their left edges align. If the page scrolls or the layout shifts, the browser keeps them together. You do not need a script.
Several details matter here:
anchor-namegoes on the invoker, or on any element you want the popover to follow. It does not have to be the button that opens the popover, but it usually is.anchor()only works on properties that are inset properties (top,left, and so on) of an absolutely or fixed positioned element. Popovers qualify because they areposition: fixed.- Each anchor name should be unique per popover. If you reuse one name on several elements, the popover binds to the last one in document order that is a valid anchor. This is a common bug in lists that repeat a button for each row. Give each row its own name, for example by setting
anchor-nameinline with a custom property.
Shorthand with position-area
For common placements, position-area is shorter than writing anchor() calls. It divides the space around the anchor into a three-by-three grid and puts the popover in the cell you name.
#menu {
margin: 0;
inset: auto;
position-anchor: --menu-button;
position-area: bottom;
}position-area: bottom centers the popover horizontally under the anchor. Other values such as top, left, right, and bottom span-right choose other cells. Use anchor() when you need exact control over each edge, and position-area when the grid cell is enough.
Staying inside the viewport
A popover near the bottom of the screen would run off the page. The position-try-fallbacks property lists alternatives the browser tries when the first placement overflows.
#menu {
margin: 0;
inset: auto;
position-anchor: --menu-button;
position-area: bottom;
position-try-fallbacks: flip-block, flip-inline;
}flip-block moves the popover above the anchor when there is no room below. flip-inline flips it to the other side horizontally. The browser picks the first option that fits.
A JavaScript fallback
Without anchoring, you measure the invoker and copy its coordinates onto the popover. Because the popover is position: fixed, viewport coordinates from getBoundingClientRect() are exactly what you need.
There is a timing detail. A closed popover has display: none, so its width and height measure as zero. The beforetoggle event fires before the popover is shown, so you can set top and left there, but you cannot measure the popover yet. The toggle event fires after it opens, so you can measure the popover and correct any overflow there.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Measured popover</title>
<style>
#tip {
margin: 0;
inset: auto;
padding: 0.5rem 0.75rem;
border: 1px solid #888;
border-radius: 6px;
}
</style>
</head>
<body>
<button id="details-btn" popovertarget="tip">Details</button>
<div id="tip" popover>Extra information about this item.</div>
<script>
const GAP = 8;
const button = document.getElementById('details-btn');
const tip = document.getElementById('tip');
tip.addEventListener('beforetoggle', (event) => {
if (event.newState !== 'open') return;
const rect = button.getBoundingClientRect();
tip.style.top = `${rect.bottom + GAP}px`;
tip.style.left = `${rect.left}px`;
});
tip.addEventListener('toggle', (event) => {
if (event.newState !== 'open') return;
const buttonRect = button.getBoundingClientRect();
const tipRect = tip.getBoundingClientRect();
const viewportWidth = document.documentElement.clientWidth;
const maxLeft = viewportWidth - tipRect.width - GAP;
if (tipRect.left > maxLeft) {
tip.style.left = `${Math.max(GAP, maxLeft)}px`;
}
if (tipRect.bottom > window.innerHeight) {
tip.style.top = `${buttonRect.top - tipRect.height - GAP}px`;
}
});
</script>
</body>
</html>This version has limits you should know about:
- It computes the position once, when the popover opens. If the user scrolls or resizes the window while it is open, the popover stays where it was. A
popover="auto"popover does not close on scroll. Either listen forscrollandresizeand call the placement code again, or close the popover when they happen. - The correction in
togglecan cause a brief visible jump, because the popover is already on screen when the second adjustment runs. For most small tooltips this is not noticeable. If it is, place the popover off-screen first and reveal it after measuring. - The flip logic only handles the bottom and right edges. A production version would also check the top and left edges.
Popover width and the anchor
Sometimes the popover should be as wide as its invoker, such as a dropdown under a form field. Anchor positioning provides anchor-size() for this:
#menu {
margin: 0;
inset: auto;
position-anchor: --menu-button;
top: anchor(bottom);
left: anchor(left);
min-width: anchor-size(width);
}Using min-width lets the popover grow if its content is wider, while never being narrower than the button. In the JavaScript version, set tip.style.minWidth = ${rect.width}px` inside beforetoggle`.
Common mistakes
- Setting
topandleftwithoutmargin: 0andinset: auto. The popover stays centered. - Expecting the popover to be positioned relative to its parent in the DOM.
- Measuring the popover inside
beforetoggle. Its size is zero because it is not rendered yet. - Reusing one
anchor-namefor many invokers, so every popover attaches to the same button. - Assuming a hard-coded offset works on small screens, where the popover can overflow.
Exercise
A developer adds top: 40px; left: 20px; to a [popover] rule. The popover still appears in the center of the page. What is the cause, and what two declarations fix it?
Show answer
The user agent styles set inset: 0 and margin: auto on popovers, and that combination keeps the box centered in the viewport, so the extra top and left values do not move it. Adding margin: 0 and inset: auto (before the top and left values) removes the centering, and then the offsets take effect.
Exercise
You position a popover with JavaScript and read tip.getBoundingClientRect().width inside a beforetoggle handler. The result is 0. Why, and which event should you use to read the size?
Show answer
Before it opens, the popover has display: none, so it has no rendered size. The beforetoggle event fires before the popover is shown. Use the toggle event, which fires after the popover is open, to measure it.
Exercise
Write the two CSS declarations that make a popover named #menu sit centered below an invoker whose anchor-name is --menu-button, assuming margin: 0; inset: auto; is already set.
Show answer
position-anchor: --menu-button; and position-area: bottom;