CSS 锚点定位

简介

Chrome 125 引入了一个 CSS Anchor Position API,它能够让元素相对于页面上的其它元素(锚点)进行定位。相比于传统的定位方式,锚点定位则更加简单灵活。

接下来就简单介绍下锚点定位的基本使用

基本定位

设置锚点,将 anchor-name 属性应用于所选元素,并为其分配唯一标识符,标识符前面必须添加双短划线。

css 复制代码
.anchor-ele {
  anchor-name: --anchor-el;
}

连接锚点.anchor-ele 将充当锚点,引导其它元素连接至此锚点。可通过以下两种方式连接:隐式锚点 和 显式锚点,区别在于是否在 anchor() 函数中指定锚点名称,显式锚点就显得更加灵活,可用于锚定多个元素。

css 复制代码
/* 隐式锚点 */
.position-ele {
  position-anchor: --anchor-el;
  top: anchor(bottom);
}

/* 显式锚点 */
.position-ele {
  top: anchor(--anchor-el bottom);
}

锚点定位基于 CSS 绝对定位。如需使用定位值,您需要为定位的元素添加 position: absolute。然后,使用 anchor() 函数应用定位值。

css 复制代码
.position-ele {
  position: absolute;
  bottom: anchor(--anchor-el top);
}

多个锚点

元素可以绑定至多个锚点。在以下示例中,元素的左上角固定在第一个锚点的右下角,元素的右下角固定在第二个锚点的左上角:

css 复制代码
.one {
  anchor-name: --one;
}
.two {
  anchor-name: --two;
}
.anchored {
  position: absolute;
  top: anchor(--one bottom);
  left: anchor(--one right);
  right: anchor(--two left);
  bottom: anchor(--two top);
}

调整锚点位置

如果当元素到达页面边缘的时候需要调整位置,可以创建备用锚点位置。(使用 @position-try 指令和 position-try-options 属性)

接下来写一个 select 浮层来展示效果:

首先展示一下初始化的界面效果

html 复制代码
<input class="input" type="text" />
<div class="overlay"></div>
css 复制代码
.input {
  anchor-name: --anchor-input;
}
.overlay {
  width: 400px;
  height: 200px;
  background-color: #fff;
  box-shadow: 0 1px 10px rgba(0, 0, 0, 0.1);
  position: absolute;
  position-anchor: --anchor-input;
  inset-area: bottom span-right;
}

创建四个备用位置,浮层的位置分别在 左上、右上、左下、右下,对应了控件在屏幕四个角的时候浮层的位置调整。

css 复制代码
@position-try --top-left {
  inset-area: top span-left;
}
@position-try --top-right {
  inset-area: top span-right;
}
@position-try --bottom-left {
  inset-area: bottom span-left;
}
@position-try --bottom-right {
  inset-area: bottom span-right;
}
.overlay {
  position-try-options: --bottom-left, --bottom-right, --top-left, --top-right;
}

当控件在左上角的时候浮层展示效果:

跟初始化的位置是一样的

当控件在右上角的时候浮层展示效果:

当控件在左下角的时候浮层展示效果:

当控件在右下角的时候浮层展示效果:

总结

从以上几个示例来看,只用简单的几行代码,就能够实现复杂的布局效果,足以见得这个功能的强大!

CSS Anchor Positioning API 的推出或许是 Web 开发领域的颠覆性改变,大家可以尝试使用这项新特性,以便为未来的广泛应用做好准备。

相关推荐
涛涛ing1 小时前
OpenAI Astra 泄露:零样本生成 3D 网页,前端开发者慌了吗?
前端
ssshooter2 小时前
现在网页都能提供 MCP 了?!
前端·人工智能·程序员
杉氧2 小时前
状态管理变迁史:为什么我们放弃了 Redux 选择 Zustand?
android·前端·react native
cidy_982 小时前
OpenCode 手动配置火山方舟 Agent Plan 教程
前端
鹏多多2 小时前
PC 网站接入微信登录,这 10 个坑我替你踩完了!
前端·javascript·vue.js
律宏阔3 小时前
微信小程序使用 Orval + OpenAPI 自动生成接口:Axios 兼容踩坑记录
前端·微信小程序
律宏阔3 小时前
微信小程序集成 TDesign 完整记录:解决 NPM packages not found
前端·微信小程序
律宏阔3 小时前
微信小程序 ECharts 瘦身实战:分包异步化 + componentPlaceholder 避开主包 2MB 限制
前端·微信小程序
夏天要喝冰可乐3 小时前
从 Idea 到开源插件:我用 Vibe Coding 做了「文章摆渡」
前端·ai编程·vibecoding
小小小小宇3 小时前
pi agent
前端