随着 Chrome 125 中 CSS Anchor Position API 的引入,相对于一个元素定位另一个元素从未如此简单。这是实现复杂定位用例,如弹出工具提示的好方法。
然而,CSS 锚点定位不仅可以用于工具提示,还可以用于创建基本的流程图。在这篇文章中,我们将学习如何使用 CSS 锚点定位来创建流程图。
本文不会涵盖完整的锚点定位 API。要深入了解 CSS 锚点定位 API,请查看 Chrome 开发者博客文章 CSS 锚点定位 API 简介。
基本定位
CSS 锚点定位是相对于另一个元素定位元素的好方法。
要创建我们的第一个锚定元素,我们需要为 div 提供一个名称"one",以便我们可以引用它。锚点名称必须是唯一的,以两个破折号开头 --。
.one {
anchor-name: --anchor-one;
}
接下来,我们需要为第二个div 提供锚点定位。我们将使用 anchor(--anchor-one top) 来定位。
.two {
position-anchor: --anchor-one;
bottom: anchor(--anchor-one top);
justify-self: anchor-center;
}
多个锚点
使用 CSS 锚点定位,我们可以同时将一个元素锚定到其他两个元素。
就像 div “one” 一样,我们为 div “two” 分配一个锚点名称,以便我们为第三个 div 引用。
.one {
anchor-name: --anchor-one;
}
.two {
anchor-name: --anchor-two;
}
在本例中,我们使用 center 而不是 side 来定位 relative to。这会为锚点创建重叠效果。
.three {
top: anchor(--anchor-one center);
bottom: anchor(--anchor-two center);
left: anchor(--anchor-one center);
right: anchor(--anchor-two center);
}
基本流程图节点
通过将元素锚定在两个节点之间,我们可以通过一些额外的 CSS ,创建一个类似流程图的效果。
对于第三个 div,我们可以更改背景颜色。使用背景渐变在 div 中创建线条效果。
.line {
anchor-name: --line;
top: anchor(--one center);
bottom: anchor(--two center);
left: anchor(--one center);
right: anchor(--two center);
position: absolute;
z-index: -1;
background: linear-gradient(#2d2d2d, #2d2d2d) no-repeat center/2px 100%;
}
现在我们有了居中定位的线,我们可以使用 CSS 伪元素在线的每一侧创建箭头。
.line::before {
position: fixed;
display: block;
content: '';
background: #2d2d2d;
height: 2px;
}
.line::before {
bottom: anchor(--one center);
left: anchor(--one right);
right: anchor(--line center);
}
然后再次在线路的另一侧使用 CSS 。
.line::before,
.line::after {
position: fixed;
display: block;
content: '';
background: #2d2d2d;
height: 2px;
}
.line::before {
bottom: anchor(--one center);
left: anchor(--one right);
right: anchor(--line center);
}
.line::after {
bottom: anchor(--two center);
right: anchor(--two left);
left: anchor(--line center);
}
多节点流程图
上面的方法可以通过提供额外的节点和链接锚点来扩展。但是,当我们添加额外的行时,我们需要根据节点的相对位置来翻转线的方向。CSS position-try-options 允许元素回退位置。
.line {
position-try-options: flip-block, flip-inline, flip-block flip-inline;
...
}
可拖动流程图