CSS: Popovers and anchors
Published by marco on
The article Do JavaScript frameworks still need portals? by Ollie Williams (Fully Stacked) explains a bit more about the relationship between dialog
, popover
, and anchor
as well as how these elements have made “portal” support in frameworks obsolete. The following ~20-minute video shows how to use only CSS and HTML to position and display elements, regardless of their nesting in the document.
The main example uses CSS anchor positioning (MDN), position-try (MDN) and :popover-open (MDN). You can use position-try
to direct the browser to adjust the appearance of the popover when there isn’t enough “space” on-screen at its default position. You can also animate everything.
.user-button {
padding: 0;
border-radius: 100vw;
aspect-ratio: 1;
anchor-name: --profile-button;
}
.profile-menu {
position: absolute;
position-anchor: --profile-button
top: anchor (bottom) ;
right: anchor(right);
margin: 0;
inset: auto;
margin-block-start: 6px;
}
.profile-menu:popover-open {
display: grid;
}
@position-try --bottom {
inset: unset;
top: anchor(bottom);
right: anchor(right);
}