Welcome to “Anchor Positioning 101†where we will be exploring this interesting new CSS feature. Our textbook for this class will be the extensive “Anchor Positioning Guide†that Juan Diego Rodriguez published here on CSS-Tricks.
I’m excited for this one. Some of you may remember when CSS-Tricks released the “Flexbox Layout Guide†or the “Grid Layout Guide†— I certainly do and still have them both bookmarked! I spend a lot of time flipping between tabs to make sure I have the right syntax in my “experimental†CodePens.
I’ve been experimenting with CSS anchor positioning like the “good old days†since Juan published his guide, so I figured it’d be fun to share some of the excitement, learn a bit, experiment, and of course: build stuff!
CSS Anchor Positioning introduction
Anchor positioning lets us attach — or “anchor†— one element to one or more other elements. More than that, it allows us to define how a “target†element (that’s what we call the element we’re attaching to an anchor element) is positioned next to the anchor-positioned element, including fallback positioning in the form of a new @position-try
at-rule.
The most hand-wavy way to explain the benefits of anchor positioning is to think of it as a powerful enhancement to position: absolute;
as it helps absolutely-positioned elements do what you expect. Don’t worry, we’ll see how this works as we go.
Anchor positioning is currently a W3C draft spec, so you know it’s fresh. It’s marked as “limited availability†in Baseline which at the time of writing means it is limited to Chromium-based browsers (versions 125+). That said, the considerate folks over at Oddbird have a polyfill available that’ll help out other browsers until they ship support.
This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.
Desktop
Chrome | Firefox | IE | Edge | Safari |
---|---|---|---|---|
125 | No | No | 125 | No |
Mobile / Tablet
Android Chrome | Android Firefox | Android | iOS Safari |
---|---|---|---|
131 | No | 131 | No |
Oddbird contributes polyfills for many new CSS features and you (yes, you!) can support their work on Github or Open Collective!
Tab Atkins-Bittner, contributing author to the W3C draft spec on anchor positioning, spoke on the topic at CSS Day 2024. The full conference talk is available on YouTube:
Here at CSS-Tricks, Juan demonstrated how to mix and match anchor positioning with view-driven animations for an awesome floating notes effect:
Front-end friend Kevin Powell recently released a video demonstrating how “CSS Popover + Anchor Positioning is Magicalâ€.
And finally, in the tradition of “making fun games to learn CSS,†Thomas Park released Anchoreum (a “Flexbox Froggy“-type game) to learn about CSS anchor positioning. Highly recommend checking this out to get the hang of the position-area
property!
The homework
OK, now that we’re caught up on what CSS anchor positioning is and the excitement surrounding it, let’s talk about what it does. Tethering an element to another element? That has a lot of potential. Quite a few instances I can remember where I’ve had to fight with absolute
positioning and z-index
in order to get something positioned just right.
Let’s take a quick look at the basic syntax. First, we need two elements, an anchor-positioned element and the target element that will be tethered to it.
<!-- Anchor element -->
<div id="anchor">
Anchor
</div>
<!-- Target element -->
<div id="target">
Target
</div>
We set an element as an anchor-positioned element by providing it with an anchor-name
. This is a unique name of our choosing, however it needs the double-dash prefix, like CSS custom properties.
#anchor {
anchor-name: --anchor;
}
As for our target element, we’ll need to set position: absolute;
on it as well as tell the element what anchor to tether to. We do that with a new CSS property, position-anchor
using a value that matches the anchor-name
of our anchor-positioned element.
#anchor {
anchor-name: --anchor;
}
#target {
position: absolute;
position-anchor: --anchor;
}
May not look like it yet, but now our two elements are attached. We can set the actual positioning on the target element by providing a position-area
. To position our target element, position-area
creates an invisible 3×3 grid over the anchor-positioned element. Using positioning keywords, we can designate where the target element appears near the anchor-positioned element.
#target {
position: absolute;
position-anchor: --anchor;
position-area: top center;
}
Now we see that our target element is anchored to the top-center of our anchor-positioned element!
Anchoring pseudo-elements
While playing with anchor positioning, I noticed you can anchor pseudo-elements, just the same as any other element.
#anchor {
anchor-name: --anchor;
&::before {
content: "Target";
position: absolute;
position-anchor: --anchor;
left: anchor(center);
bottom: anchor(center);
}
}
Might be useful for adding design flourishes to elements or adding functionality as some sort of indicator.
Moving anchors
Another quick experiment was to see if we can move anchors. And it turns out this is possible!
Notice the use of anchor()
functions instead of position-area
to position the target element.
#target {
position: absolute;
position-anchor: --anchor-one;
top: anchor(bottom);
left: anchor(left);
}
CSS anchor functions are an alternate way to position target elements based on the computed values of the anchor-positioned element itself. Here we are setting the target element’s top property value to match the anchor-positioned element’s bottom value. Similarly, we can set the target’s left
property value to match the anchor-positioned element’s left
value.
Hovering over the container element swaps the position-anchor
from --anchor-one
to --anchor-two
.
.container:hover {
#target {
position-anchor: --anchor-two;
}
}
We are also able to set a transition
as we position the target using top
and left
, which makes it swap smoothly between anchors.
Extra experimental
Along with being the first to release CSS anchor-positioning, the Chrome dev team recently released new pseudo-selectors related to the <details>
and <summary>
elements. The ::details-content
pseudo-selector allows you to style the “hidden†part of the <details>
element.
With this information, I thought: “can I anchor it?†and sure enough, you can!
Again, this is definitely not ready for prime-time, but it’s always fun to experiment!
Practical examinations
Let’s take this a bit further and tackle more practical challenges using CSS anchor positioning. Please keep in mind that all these examples are Chrome-only at the time of writing!
Tooltips
One of the most straightforward use cases for CSS anchor positioning is possibly a tooltip. Makes a lot of sense: hover over an icon and a label floats nearby to explain what the icon does. I didn’t quite want to make yet another tutorial on how to make a tooltip and luckily for me, Zell Liew recently wrote an article on tooltip best practices, so we can focus purely on anchor positioning and refer to Zell’s work for the semantics.
Now, let’s check out one of these tooltips:
<!-- ... -->;
<li class="toolbar-item">;
<button type="button"
id="inbox-tool"
aria-labelledby="inbox-label"
class="tool">
<svg id="inbox-tool-icon">
<!-- SVG icon code ... -->
</svg>
</button>
<div id="inbox-label" role="tooltip">
<p>Inbox</p>
</div>
</li>
<!-- ... -->
The HTML is structured in a way where the tooltip element is a sibling of our anchor-positioned <button>
, notice how it has the [aria-labelledby]
attribute set to match the tooltip’s [id]
. The tooltip itself is a generic <div>
, semantically enhanced to become a tooltip with the [role="tooltip"]
attribute. We can also use [role="tooltip"]
as a semantic selector to add common styles to tooltips, including the tooltip’s positioning relative to its anchor.
First, let’s turn our button into an anchored element by giving it an anchor-name
. Next, we can set the target element’s position-anchor
to match the anchor-name
of the anchored element. By default, we can set the tooltip’s visibility
to hidden
, then using CSS sibling selectors, if the target element receives hover
or focus-visible
, we can then swap the visibility
to visible
.
/* Anchor-positioned Element */
#inbox-tool {
anchor-name: --inbox-tool;
}
/* Target element */
[role="tooltip"]#inbox-label {
position-anchor: --inbox-tool
}
/* Target positioning */
[role="tooltip"] {
position: absolute;
position-area: end center;
/* Hidden by default */
visibility: hidden;
}
/* Visible when tool is hovered or receives focus */
.tool:hover + [role="tooltip"],
.tool:focus-visible + [role="tooltip"] {
visibility: visible;
}
Ta-da! Here we have a working, CSS anchor-positioned tooltip!
As users of touch devices aren’t able to hover over elements, you may want to explore toggletips instead!
Floating disclosures
Disclosures are another common component pattern that might be a perfect use case for anchor positioning. Disclosures are typically a component where interacting with a toggle will open and close a corresponding element. Think of the good ol’ <detail>/<summary>
HTML element duo, for example.
Currently, if you are looking to create a disclosure-like component which floats over other portions of your user interface, you might be in for some JavaScript, absolute
positioning, and z-index
related troubles. Soon enough though, we’ll be able to combine CSS anchor positioning with another newer platform feature [popover]
to create some incredibly straightforward (and semantically accurate) floating disclosure elements.
The Popover API provides a non-modal way to elevate elements to the top-layer
, while also baking in some great functionality, such as light dismissals.
Zell also has more information on popovers, dialogs, and modality!
One of the more common patterns you might consider as a “floating disclosureâ€-type component is a dropdown menu. Here is the HTML we’ll work with:
<nav>
<button id="anchor">Toggle</button>
<ul id="target">
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
<li><a href="#">Link 3</a></li>
</ul>
</nav>
We can set our target element, in this case the <ul>
, to be our popover element by adding the [popover]
attribute.
To control the popover, let’s add the attribute [popoveraction="toggle"]
to enable the button as a toggle, and point the [popovertarget]
attribute to the [id]
of our target element.
<nav>
<button id="anchor"
popoveraction="toggle"
popovertarget="target">
Toggle
</button>
<ul id="target" popover>
<li><a href="#">Link 1</a></li>
<li><a href="#">Link 2</a></li>
<li><a href="#">Link 3</a></li>
</ul>
</nav>
No JavaScript is necessary, and now we have a toggle-able [popover]
disclosure element! The problem is that it’s still not tethered to the anchor-positioned element, let’s fix that in our CSS.
First, as this is a popover, let’s add a small bit of styling to remove the intrinsic margin
popovers receive by default from browsers.
ul[popover] {
margin: 0;
}
Let’s turn our button into an anchor-positioned element by providing it with an anchor-name
:
ul[popover] {
margin: 0;
}
#anchor {
anchor-name: --toggle;
}
As for our target element, we can attach it to the anchor-positioned element by setting its position to absolute
and the position-anchor
to our anchor-positioned element’s anchor-name
:
ul[popover] {
margin: 0;
}
#anchor {
anchor-name: --toggle;
}
#target {
position: absolute;
position-anchor: --toggle;
}
We can also adjust the target’s positioning near the anchor-positioned element with the position-area
property, similar to what we did with our tooltip.
ul[popover] {
margin: 0;
}
#anchor {
anchor-name: --toggle;
}
#target {
position: absolute;
position-anchor: --toggle;
position-area: bottom;
width: anchor-size(width);
}
You may notice another CSS anchor function in here, anchor-size()
! We can set the target’s width
to match the width of the anchor-positioned element by using anchor-size(width)
.
There is one more neat thing we can apply here, fallback positioning! Let’s consider that maybe this dropdown menu might sometimes be located at the bottom of the viewport, either from scrolling or some other reason. We don’t really want it to overflow or cause any extra scrolling, but instead, swap to an alternate location that is visible to the user.
Anchor positioning makes this possible with the postion-try-fallbacks
property, a way to provide an alternate location for the target element to display near an anchor-positioned element.
#target {
position: absolute;
position-anchor: --toggle;
position-area: bottom;
postion-try-fallbacks: top;
width: anchor-size(width);
}
To keep things simple for our demo, we can add the opposite value of the value of the postion-area
property: top
.
Shopping cart component
We know how to make a tooltip and a disclosure element, now let’s build upon what we’ve learned so far and create a neat, interactive shopping cart component.
Let’s think about how we want to mark this up. First, we’ll need a button with a shopping cart icon:
<button id="shopping-cart-toggle">
<svg id="shopping-cart-icon" />
<!-- SVG icon code ... -->
</svg>
</button>
We can already reuse what we learned with our tooltip styles to provide a functioning label for this toggle. Let’s add the class .tool
to the button, then include a tooltip as our label.
<!-- Toggle -->
<button id="shopping-cart-toggle"
aria-labelledby="shopping-cart-label"
class="tool">
<svg id="shopping-cart-icon" />
<!-- SVG icon code ... -->
</svg>
</button>
<!-- Tooltip -->
<div id="shopping-cart-label"
role="tooltip"
class="tooltip">
<p>Shopping Cart</p>
</div>
We’ll need to specify our <button>
is an anchor-positioned element in CSS with an anchor-name
, which we can also set as the tooltip’s position-anchor
value to match.
button#shopping-cart-toggle {
anchor-name: --shopping-cart-toggle;
}
[role="tooltip"]#shopping-cart-label {
position-anchor: --shopping-cart-toggle;
}
Now we should have a nice-looking tooltip labeling our shopping cart button!
But wait, we want this thing to do more than that! Let’s turn it into a disclosure component that reveals a list of items inside the user’s cart. As we are looking to have a floating user-interface with a few actions included, we should consider a <dialog>
element. However, we don’t necessarily want to be blocking background content, so we can opt for a non-modal dialog using the[popover]
attribute again!
<!-- Toggle -->
<button id="shopping-cart-toggle"
aria-labelledby="shopping-cart-label"
class="tool"
popovertarget="shopping-cart"
popoveraction="toggle">
<svg id="shopping-cart-icon" />
<!-- SVG icon code ... -->
</svg>
</button>
<!-- Tooltip -->
<div id="shopping-cart-label"
role="tooltip"
class="tooltip">
<p>Shopping Cart</p>
</div>
<!-- Shopping Cart -->
<dialog id="shopping-cart" popover>
<!-- Shopping cart template... -->
<button popovertarget="shopping-cart" popoveraction="close">
Dismiss Cart
</button>
</dialog>
To control the popover, we’ve added [popovertarget="shopping-cart"]
and [popoveraction="toggle"
] to our anchor-positioned element and included a second button within the <dialog>
that can also be used to close the dialog with [popoveraction="close"]
.
To anchor the shopping cart <dialog>
to the toggle, we can set position-anchor
and position-area
:
#shopping-cart {
position-anchor: --shopping-cart;
position-area: end center;
}
At this point, we should take a moment to realize that we have tethered two elements to the same anchor!
We won’t stop there, though. There is one more enhancement we can make to really show how helpful anchor positioning can be: Let’s add a notification badge to the element to describe how many items are inside the cart.
Let’s place the badge inside of our anchor-positioned element this time.
<!-- Toggle -->
<button id="shopping-cart-toggle"
aria-labelledby="shopping-cart-label"
class="tool"
popovertarget="shopping-cart"
popoveraction="toggle">
<svg id="shopping-cart-icon" />
<!-- SVG icon code ... -->
</svg>
<!-- Notification Badge -->
<div id="shopping-cart-badge" class="notification-badge">
1
</div>
</button>
<!-- ... -->
We can improve our tooltip to include verbiage about how many items are in the cart:
<!-- Tooltip -->
<div id="shopping-cart-label"
role="tooltip">
<p>Shopping Cart</p>
<p>(1 item in cart)</p>
</div>
Now the accessible name of our anchor-positioned element will be read as Shopping Cart (1 item in cart)
, which helps provide context to assistive technologies like screen readers.
Let’s tether this notification badge to the same anchor as our tooltip and shopping cart <dialog>
, we can do this by setting the position-anchor
property of the badge to --shopping-cart-toggle
:
#shopping-cart-badge {
position: absolute;
position-anchor: --shopping-cart-toggle;
}
Let’s look at positioning. We don’t want it below or next to the anchor, we want it overlapping, so we can use CSS anchor functions to position it based on the anchor-positioned element’s dimensions.
#shopping-cart-badge {
position: absolute;
position-anchor: --shopping-cart-toggle;
bottom: anchor(center);
left: anchor(center);
}
Here we are setting the bottom
and left
of the target element to match the anchor’s center
. This places it in the upper-right corner of the SVG icon!
Folks, this means we have three elements anchored now. Isn’t that fantastic?
Combining things
To put these anchor-positioned elements into perspective, I’ve combined all the techniques we’ve learned so far into a more familiar setting:
Disclosure components, dropdown menus, tooltips (and toggletips!), as well as notification badges all made much simpler using CSS anchor positioning!
Final project
As a final project for myself (and to bring this whole thing around full-circle), I decided to try to build a CSS anchor-positioned-based onboarding tool. I’ve previously attempted to build a tool like this at work, which I called “HandHoldJS†and it… well, it didn’t go so great. I managed to have a lot of the core functionality working using JavaScript, but it meant keeping track of quite a lot of positions and lots of weird things kept happening!
Let’s see if we can do better with CSS anchor positioning.
Feel free to check out the code on CodePen! I went down quite a rabbit hole on this one, so I’ll provide a bit of a high-level overview here.
<hand-hold>
is a native custom element that works entirely in the light DOM
. It sort of falls into the category of an HTML web component, as it is mostly based on enabling its inner HTML. You can specify tour stops to any element on the page by adding [data-tour-stop]
attributes with values in the order you want the tour to occur.
Inside the <hand-hold>
element contains a <button>
to start the tour, a <dialog>
element to contain the tour information, <section>
elements to separate content between tour stops, a fieldset[data-handhold-navigation]
element which holds navigation radio buttons, as well as another <button>
to end the tour.
Each <section>
element corresponds to a tour stop with a matching [data-handhold-content]
attribute applied. Using JavaScript, <hand-hold>
dynamically updates tour stops to be anchor-positioned elements, which the <dialog>
can attach itself (there is a sneaky pseudo-element attached to the anchor to highlight the tour stop element!).
Although the <dialog>
element is attached via CSS anchor positioning, it also moves within the DOM to appear next to the anchor-position element in the accessibility tree. The (well-meaning) intention here is to help provide more context to those who may be navigating via assistive devices by figuring out which element the dialog is referring to. Believe me, though, this thing is far from perfect as an accessible user experience.
Also, since the <dialog>
moves throughout the DOM, unfortunately, a simple CSS transition would not suffice. Another modern browser feature to the rescue yet again, as we can pass a DOM manipulation function into a View Transition, making the transitions feel smoother!
There is still quite a lot to test with this, so I would not recommend using <hand-hold>
in a production setting. If for no other reason than browser support is quite limited at the moment!
This is just an experiment to see what I could cook up using CSS anchor positioning, I’m excited for the potential!
Class dismissed!
After seeing what CSS anchor positioning is capable of, I have suspicions that it may change a lot of the ways we write CSS, similar to the introduction of flexbox or grid.
I’m excited to see what other user interface patterns can be accomplished with anchor positioning, and I’m even more excited to see what the community will do with it once it’s more broadly available!
One of Those “Onboarding†UIs, With Anchor Positioning originally published on CSS-Tricks, which is part of the DigitalOcean family. You should get the newsletter.
Source: Read MoreÂ