Scope Anchors and Plan a Fallback

In the last video, the cordless drill’s Options menu learned to open under its button and to flip above it near the bottom of the window. The other three cards on Kwame’s catalog page still open their menus in the middle of the window.

In this lesson, you’ll anchor every card’s menu to its own button with one set of rules, keep the menus usable in browsers without anchor positioning, and check them with a keyboard and a screen reader. Start by moving the drill’s rules to all four cards.

Keep Each Anchor Name in Its Card

The video’s rules reach one button and one menu: an attribute selector picks the drill’s button, and an id selector picks its menu. Every card uses the same classes, so select by those instead. Open catalog.html from this lesson’s starting site in your live preview, and replace the last two rules in styles.css with these:

Language: CSS
.options-button {
  anchor-name: --options;
}

.options-menu {
  position-anchor: --options;
  position-area: bottom;
  position-try-fallbacks: flip-block;
}

Watch out: anchor names are global, so a menu uses the last element on the page with that name. In this lesson’s run, the step ladder’s menu opened above the hedge trimmer’s button, in the last card, instead of its own.

The anchor-scope property fixes that by limiting a name to an element and everything inside it. Add this rule above the other two:

Language: CSS
.tool-card {
  anchor-scope: --options;
}

Each card now keeps its own --options. A menu looks for that name only inside its card, where the one match is its own Options button. Here’s the button each menu finds in two of the cards, before and after the rule:

Without anchor-scope, both menus anchor to the trimmer's Options button. With it, each menu anchors to its own card's button.
One Global Name Versus One Name per Card

Save, scroll down to the step ladder’s card, and click its Options button:

The step ladder's menu, with the links See the tool page, Reserve it and Report a problem, opens right under the step ladder card's Options button.
Each Menu Anchored Inside Its Own Card

The ladder’s menu now opens under its own button, as does every other menu.

If you’re not sure why one rule sent every menu to the same button, the mentor can trace it with you:

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.