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

相关推荐
JavaGuide2 小时前
刚刚,阿里版 Codex 上线了匿名模型 HungerG,无限 Token!
前端·后端
zhanlang02172 小时前
HTML 零基础入门到企业实战全套教程【第九章 9.3】移动端 HTML 基础适配入门
前端·html
用户69371750013842 小时前
AI 帮我写了大半年的代码,我却越来越不会写代码了
前端·后端·github
skywalk81632 小时前
把「假成功」赶出工具层:lightharness 两天升级复盘(4×5 模式矩阵 + 工具层 5 个缺陷)
开发语言·前端·人工智能·lightharness
彭亚川Allen2 小时前
从零手搓 RAG:用 Elasticsearch 存储与检索向量
前端·后端·面试
jerrywus2 小时前
15 个可以直接安装的 AI Agent Skills:按场景挑
前端·agent·claude
涛涛ing3 小时前
用了三年微前端,我们终于把它拆成了单体应用
前端
去伪存真3 小时前
《最终版》《打死不改版》全传一遍?RAG 系统文件去重实战
前端
anyup3 小时前
【全端支持】 uni-app x 专用请求库:axios 写法,多实例、拦截器、可中断、上传下载
前端·uni-app·unix
费曼学习法4 小时前
6 个 MCP Server 传输层重写实录:超时率 12% → 0.3%
前端·后端