今日已更新 304 条资讯 | 累计 31572 条内容
关于我们

CSS Anchor Positioning: Building Tooltips Without JavaScript Positioning Hacks

Niharika Pujari 2026年08月14日 11:16 0 次阅读 来源:Dev.to

Introduction Positioning a tooltip sounds simple. Put a small box next to a button. Done. But anyone who has built one knows that it can quickly turn into: position: absolute calculating coordinates listening for resize events handling scrolling checking whether the tooltip fits on screen and sometimes pulling in an entire positioning library Modern CSS is starting to change that. CSS Anchor Positioning lets us position one element relative to another directly in CSS. Let's look at what that means with a very simple tooltip. What Is CSS Anchor Positioning? CSS Anchor Positioning allows one element to act as an anchor and another element to position itself relative to that anchor. Think about UI components such as: Tooltips Dropdown menus Popovers Context menus Floating labels These elements usually need to appear next to another element. Instead of calculating where they belong with JavaScript, we can now describe that relationship in CSS. Conceptually, we're saying: "This button is my anchor. Position this tooltip relative to it." A Simple Example Imagine we have a button: <button class= "info-button" > More info </button> <div class= "tooltip" > Your changes are saved automatically. </div> We want the tooltip to appear directly below the button. First, let's make the button an anchor. .info-button { anchor-name : --info-button ; } We've now given the button an anchor name. Next, connect our tooltip to it. .tooltip { position : absolute ; position-anchor : --info-button ; top : anchor ( bottom ); left : anchor ( left ); margin-top : 8px ; } That's the interesting part. top : anchor ( bottom ); tells the browser: Position the top of the tooltip at the bottom of the anchor. And: left : anchor ( left ); aligns its left side with the button. No getBoundingClientRect() . No coordinate calculations. No resize listener just to figure out where the tooltip belongs. Why Is This Useful? Before Anchor Positioning, we often had to manage positioning ourselves. A simplified Jav

本文内容来源于互联网,版权归原作者所有
查看原文