brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: CSS anchor positioning places a menu next to its button without JavaScript

Css
~/tips/tip-css-anchor-position-menu

.menu-button {

A dropdown or tooltip sticks to the element that opens it, and flips when space runs out.

Positioning a tooltip under a button used to mean measuring with JavaScript on every scroll and resize. Anchor positioning lets the browser do that work.

.menu-button {
  anchor-name: --menu-btn;
}
.menu {
  position: absolute;
  position-anchor: --menu-btn;
  position-area: bottom span-right;
  position-try-fallbacks: flip-block;
}

anchor-name gives the button a name that starts with two dashes, like a custom property. The menu points to it with position-anchor and position-area puts it on a grid around the anchor: here below the button, starting at its left edge and extending to the right. flip-block tells the browser to try the spot above the button when there is no room below.

I like to combine it with the popover attribute, so the menu also sits in the top layer and closes on Escape.

It landed in Chrome 125, Safari 26 and Firefox 147, so it is fairly new. Older Safari versions on phones are still around, and there the menu just falls back to normal absolute positioning, which can land it somewhere odd. Give it a sensible fallback position or wrap the anchor rules in @supports (anchor-name: --a).

Further reading: MDN: Using CSS anchor positioning, MDN: position-area

More Css tips CSS Overview in Chrome DevTools audits the colors and fonts of a page .notice:empty { .toast { article { counter-reset: h2; } .toolbar { All Css tips (66) All topics

Link