This demo shows the effect of position-try-order
.
HTML
The HTML includes two <div>
elements that will become an anchor and an anchor-positioned element, and a <form>
containing radio buttons allowing you to select different values of position-try-order
.
<div class="anchor">⚓︎</div>
<div class="infobox">
<p>This is an information box.</p>
</div>
<form>
<fieldset>
<legend>Choose a try order</legend>
<div>
<label for="radio-normal">normal</label>
<input
type="radio"
id="radio-normal"
name="position-try-order"
value="normal"
checked />
</div>
<div>
<label for="radio-most-height">most-height</label>
<input
type="radio"
id="radio-most-height"
name="position-try-order"
value="most-height" />
</div>
</fieldset>
</form>
CSS
In the CSS, the anchor is given an anchor-name
and has a large margin
to position it toward the top center of the viewport:
.anchor {
anchor-name: --myAnchor;
margin: 90px auto;
}
We then include a custom position option named --custom-bottom
which positions the element below the anchor and gives it an appropriate margin:
@position-try --custom-bottom {
top: anchor(bottom);
bottom: unset;
margin-top: 10px;
}
We initially position the element above its anchor, and then give it our custom position option using the position-try
shorthand, which also sets the position-try-order
property to normal
:
.infobox {
position: fixed;
position-anchor: --myAnchor;
bottom: anchor(top);
margin-bottom: 10px;
justify-self: anchor-center;
position-try: normal --custom-bottom;
}
JavaScript
Finally, we include some JavaScript. This sets a change
event handler on the radio buttons so that, when a new value is selected, that value is applied to the infobox's position-try-order
property.
const infobox = document.querySelector(".infobox");
const form = document.forms[0];
const radios = form.elements["position-try-order"];
for (const radio of radios) {
radio.addEventListener("change", setTryOrder);
}
function setTryOrder(e) {
const tryOrder = e.target.value;
infobox.style.positionTryOrder = tryOrder;
}
Result
Try selecting the most-height
order option. This has the effect of applying --custom-bottom
as a position try fallback option, which positions the element below the anchor. This occurs because there is more vertical space below the anchor than there is above it.