Anchor positioning allows you to place an element on the page based on where another element is. It makes it easier to create responsive menus and tooltips with less code using only CSS. Here’s how it works. Let’s say you have an avatar in your nav, like this: When you click the avatar, you want a menu to appear right below it. The clicking interaction can be handled with just CSS using the Popover API. But once you click, where does your menu show up? Figuring this out typically requires some JavaScript. But now, with anchor positioning, you can accomplish this with just a few lines of CSS. Anchor positioning will use where the avatar is to determine where the menu will go. For example, you might want to place it just below the avatar, nice and left-aligned, like this: Or you can have it hang out on the side of the avatar, having a party off to the right, like this: You can position it in a number of places, but I think that first example looks good. It’s something you’d frequently see on the web on sites and web apps. Let’s walk through the code of how to make it happen. The first step in placing your menu is letting it know about your avatar. A great way to think about the relationship between your avatar and your menu is to think of your menu as if it’s anchored to your avatar. With that in mind, we’ll refer to your avatar as your anchor and your menu as your target. You’ll name your anchor by declaring an anchor-name on the avatar element. Since your avatar represents your profile and is behaving like button, let’s give it a class of profile-button. Here’s what it looks like: .profile-button { anchor-name: --profile-button; } Then you’ll go to your menu (your target) and declare a position-anchor where the value is the anchor-name of the anchor that you previously declared. This is what establishes the connection and tells the target about the anchor. Let’s go to your target and declare it there: .profile-menu { position-anchor: --profile-button; } And the fina...
First seen: 2025-08-12 22:55
Last seen: 2025-08-13 00:55