This example enables changing the value of an anchor positioned element's position-visibility
property to demonstrate the effects of each value.
HTML
We specify two <div>
elements; an anchor element with a class of anchor
and a positioned element with a class of infobox
.
<div class="anchor">⚓︎</div>
<div class="infobox">
<p>This is an information box.</p>
</div>
The HTML also includes filler text to make the content taller than the viewport so scrolling is required. We've also included a <fieldset>
with a group of radio inputs with different position-visibility
values. The markup for these is not shown for the sake of brevity.
CSS
We style an anchor
<div>
as an anchor element and tether the infobox
<div>
to it. The relevant CSS is as follows:
.anchor {
anchor-name: --myAnchor;
}
.infobox {
position-anchor: --myAnchor;
position: fixed;
position-area: top span-all;
margin-bottom: 5px;
position-visibility: always;
}
JavaScript
We include a change
event handler on the radio buttons so that, when a new value is selected, we update the infobox's position-visibility
property value.
const infobox = document.querySelector(".infobox");
const radios = document.querySelectorAll('[name="position-visibility"]');
for (const radio of radios) {
radio.addEventListener("change", setPositionVisibility);
}
function setPositionVisibility(e) {
infobox.style.positionVisibility = e.target.value;
}
Result
Select different position-visibility
values and then scroll the page up and down to see their effects. With position-visibility: always
set, the positioned element will not be hidden. With position-visibility: anchors-visible
set, the positioned element will only be visible when the anchor is partially or fully on-screen. With position-visibility: no-overflow
set, the positioned element will be hidden as soon as it starts to overflow the viewport.