纯CSS实现两个元素之间折线自动相连实例页面

回到相关文章 »

效果:

代码:

CSS代码:
:root {
 --size-a: 150px;
 --size-b: 100px;
}
.circle {
    position: absolute;
    aspect-ratio: 1;
    border-radius: 50%;
}
.circle-a {
    width: var(--size-a);
    anchor-name: --a;
    background: #45ADA8;
    left: 60%;
    top: 35%;
}
.circle-b {
    width: var(--size-b);
    anchor-name: --b;
    background: #FA6900;
    left: 22%;
    top: 20%;
}
.line {
  position: absolute;
  --posA: calc(anchor(--a inside) + anchor-size(--a) / 2);
  --posB: calc(anchor(--b inside) + anchor-size(--b) / 2);
  top: var(--posA);
  bottom: var(--posB);
  left: var(--posA);
  right: var(--posB);
  /* 背景 */
  --direction: to left bottom;
  background: linear-gradient(var(--direction), transparent calc(50% - 2px), currentColor calc(50% - 2px) calc(50% + 2px), transparent calc(50% + 2px)) no-repeat;
  /* 径向渐变遮罩 */
  --mask-size-a: calc(var(--size-a) / 2 + 8px);
  --mask-size-b: calc(var(--size-b) / 2 + 8px);
  --mask-start: 0 0;
  --mask-end: right bottom;
  mask: radial-gradient(circle at var(--mask-start), #000 var(--mask-size-a), transparent var(--mask-size-a)) no-repeat, 
    radial-gradient(circle at var(--mask-end), #000 var(--mask-size-b), transparent var(--mask-size-b)) no-repeat, 
    linear-gradient(#000, #000);
  mask-composite: exclude;
  /* 不要影响点击 */
  pointer-events: none;
}
.line2 {
  top: var(--posB);
  bottom: var(--posA);
  --direction: to right bottom;
  --mask-start: left bottom;
  --mask-end: right top;
}
.line3 {
  left: var(--posB);
  right: var(--posA);
  top: var(--posB);
  bottom: var(--posA);
  --direction: to left bottom;
  --mask-start: right bottom;
  --mask-end: left top;
}
.line4 {
  left: var(--posB);
  right: var(--posA);
  --direction: to right bottom;
  --mask-start: right top;
  --mask-end: left bottom;
}
HTML代码:
<div class="circle circle-a"></div>
<div class="circle circle-b"></div>
<i class="line line1"></i> 
<i class="line line2"></i> 
<i class="line line3"></i> 
<i class="line line4"></i>