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

相关推荐
布列瑟农的星空14 分钟前
大话设计模式——观察者模式和发布/订阅模式的区别
前端·后端·架构
龙在天15 分钟前
Vue3 实现 B站 视差 动画
前端
KenXu16 分钟前
F2C Prompt to Design、AI 驱动的设计革命
前端
小鱼儿亮亮18 分钟前
canvas中画线条,线条效果比预期宽1像素且模糊问题分析及解决方案
前端·react.js
@大迁世界20 分钟前
用 popover=“hint“ 打造友好的 HTML 提示:一招让界面更“懂人”
开发语言·前端·javascript·css·html
伍哥的传说20 分钟前
Tailwind CSS v4 终极指南:体验 Rust 驱动的闪电般性能与现代化 CSS 工作流
前端·css·rust·tailwindcss·tailwind css v4·lightning css·utility-first
小鱼儿亮亮24 分钟前
使用Redux的combineReducers对数据拆分
前端·react.js
定栓31 分钟前
Typescript入门-类型断言讲解
前端·javascript·typescript
码间舞34 分钟前
你不知道的pnpm!如果我的电脑上安装了nvm,切换node版本后,那么pnpm还会共享一个磁盘的npm包吗?
前端·代码规范·前端工程化
用户15129054522037 分钟前
itoa函数
前端