Clean β’ Professional
The Anchor Positioning API allows developers to dynamically position elements relative to an βanchorβ element in the viewport. Unlike traditional CSS positioning (absolute, fixed, sticky), it automatically aligns elements, handles collisions, and adjusts when the anchor or viewport changes.
Think of it like attaching a tooltip, dropdown, or popup to a buttonβno manual calculations needed.
const anchor = document.querySelector('#button');
const popup = document.querySelector('#popup');
popup.showPopover(anchor, {
placement: 'bottom', // top, bottom, left, right
offset: 8, // distance from anchor
collision: 'flip', // flips automatically if element overflows
});
Hereβs a basic example using the Anchor Positioning API to show a tooltip near a button:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Anchor Position API Example</title>
<style>
body {
font-family: Arial, sans-serif;
padding: 50px;
}
button {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}
#tooltip {
position: absolute;
padding: 10px 15px;
background-color: #3498db;
color: white;
border-radius: 5px;
display: none;
white-space: nowrap;
}
</style>
</head>
<body>
<button id="myButton">Hover Me!</button>
<div id="tooltip">This is a tooltip using Anchor Position API.</div>
<script>
const button = document.getElementById('myButton');
const tooltip = document.getElementById('tooltip');
button.addEventListener('mouseenter', () => {
tooltip.style.display = 'block';
// Anchor Position API using getBoundingClientRect
const rect = button.getBoundingClientRect();
tooltip.style.top = `${rect.bottom + window.scrollY + 8}px`; // 8px offset
tooltip.style.left = `${rect.left + window.scrollX}px`;
});
button.addEventListener('mouseleave', () => {
tooltip.style.display = 'none';
});
</script>
</body>
</html>Β