This example shows the basic usage of a couple of predefined <try-tactic>
fallback options.
HTML
The HTML includes two <div>
elements that will become an anchor and an anchor-positioned element:
<div class="anchor">⚓︎</div>
<div class="infobox">
<p>This is an information box.</p>
</div>
CSS
We style the <body>
element to be very large, to enable both horizontal and vertical scrolling.
The anchor is given an anchor-name
and large margins to place it somewhere near the center of the visible section of the <body>
:
body {
width: 1500px;
height: 500px;
}
.anchor {
anchor-name: --myAnchor;
margin: 100px 350px;
}
The infobox is given fixed positioning, a position-anchor
property that references the anchor's anchor-name
, to associate the two together, and it is tethered to the anchor's top-left corner using a position-area
.
We include a position-try-fallbacks
list (and re-declare it with the position-try
shorthand incase the longhand property name is not yet supported), providing two predefined position-try fallback options to prevent it from overflowing when the anchor gets near the edge of the viewport, by flipping it along the inline or block axis of the anchor.
.infobox {
position: fixed;
position-anchor: --myAnchor;
position-area: top left;
position-try-fallbacks: flip-block, flip-inline;
position-try: flip-block, flip-inline;
}
Result
This gives us the following result:
Try scrolling so the anchor nears the edges:
- If you move the anchor near the top of the viewport, you will see the positioned element flip to the bottom-left of the anchor to avoid overflowing.
- If you move the anchor near the left of the viewport, you will see the positioned element flip to the top-right of the anchor to avoid overflowing.
However, if you move the anchor towards the top-left corner of the viewport, you'll notice a problem — as the positioned element starts to overflow in the block and inline direction, it flips back to its default top-left position and overflows in both directions, which is not what we want.
This is because we only gave the browser position options of flip-block
or flip-inline
. We didn't give it the option of trying both at the same time. The next example will show you how to fix this issue.