<div class="tooltip">Anchor me!</div>
<a class="anchor">The anchor</a>
@import "https://unpkg.com/open-props/open-props.min.css";
@import "https://unpkg.com/open-props/normalize.min.css";
* {
box-sizing: border-box;
}
body {
font-family: "Google Sans", sans-serif;
display: grid;
place-items: center;
min-height: 100vh;
background: var(--surface-2);
color: var(--text-1);
}
.containing-block {
position: relative;
}
.tooltip {
position: absolute;
top: calc(var(--y) * 1px);
left: calc(((var(--width) * 0.5) + var(--x)) * 1px);
transform: translate(-50%, calc(-100% - 10px));
box-shadow: var(--shadow-4);
padding: var(--size-4);
white-space: nowrap;
border-radius: var(--radius-2);
font-weight: var(--font-weight-6);
background: var(--surface-1);
border: 1px solid var(--surface-3);
}
.anchor {
background: var(--blue-4);
text-align: center;
font-weight: bold;
border-radius: var(--radius-2);
padding: var(--size-2);
}
const setAnchorPosition = (anchored, anchor) => {
const bounds = anchor.getBoundingClientRect().toJSON();
for (const [key, value] of Object.entries(bounds)) {
anchored.style.setProperty(`--${key}`, value);
}
};
const update = () => {
setAnchorPosition(
document.querySelector(".tooltip"),
document.querySelector(".anchor")
);
};
window.addEventListener("resize", update);
document.addEventListener("DOMContentLoaded", update);
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.