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 开发领域的颠覆性改变,大家可以尝试使用这项新特性,以便为未来的广泛应用做好准备。

相关推荐
小兵张健8 小时前
价值1000的 AI 工作流:Codex 通用前端协作模式
前端·aigc·ai编程
sunny_8 小时前
面试踩大坑!同一段 Node.js 代码,CJS 和 ESM 的执行顺序居然是反的?!99% 的人都答错了
前端·面试·node.js
拉不动的猪8 小时前
移动端调试工具VConsole初始化时的加载阻塞问题
前端·javascript·微信小程序
ayqy贾杰10 小时前
Agent First Engineering
前端·vue.js·面试
IT_陈寒10 小时前
SpringBoot实战:5个让你的API性能翻倍的隐藏技巧
前端·人工智能·后端
iceiceiceice11 小时前
iOS PDF阅读器段评实现:如何从 PDFSelection 精准还原一个自然段
前端·人工智能·ios
大金乄11 小时前
封装一个vue2的elementUI 表格组件(包含表格编辑以及多级表头)
前端·javascript
葡萄城技术团队12 小时前
【性能优化篇】面对万行数据也不卡顿?揭秘协同服务器的“片段机制 (Fragments)”
前端
程序员阿峰12 小时前
2026前端必备:TensorFlow.js,浏览器里的AI引擎,不写Python也能玩转智能
前端
Jans12 小时前
Shipfe — Rust 写的前端静态部署工具:一条命令上线 + 零停机 + 可回滚 + 自动清理
前端