CSS Anchor positioning
Anchor positioning is a powerful tool for creating dynamic & reusable styles. They allow you to define styles based on the context in which they are used, making it easier to create responsive & flexible designs.
Getting Started
CSS Anchor Positioning allows an element (the 'positioned element') to be positioned relative to one or more other elements (the 'anchor elements') on the page, regardless of their DOM relationship. This is particularly useful for creating tooltips, popovers, and other UI elements that need to be tethered to a trigger.
Here's a basic example of how you might set up a tooltip:
<button id="myAnchorButton">Hover me</button>
<div class="tooltip">This is a tooltip!</div>
<style>
#myAnchorButton {
anchor-name: --my-anchor;
}
.tooltip {
/* Position the tooltip using the anchor */
position: absolute;
left: anchor(--my-anchor left);
top: anchor(--my-anchor bottom);
/* Fallback positioning for browsers that don't support anchor() */
/* (This might need JavaScript or different CSS for a robust fallback) */
margin-top: 5px;
/* Basic styling */
background-color: #333;
color: white;
padding: 5px 10px;
border-radius: 4px;
display: none; /* Initially hidden */
}
#myAnchorButton:hover + .tooltip,
#myAnchorButton:focus + .tooltip { /* Show on hover/focus for demo */
display: block;
}
</style>