≪ Today I learned.
RSS購読
    公開日
    更新日
    タグ
    CSS
    著者
    ダーシノ

    CSS Anchor Positioningを使ってネットワーク図をつくる

    CSS Anchor Positioningを使うとターゲット要素(アンカー要素)の位置を簡単に取得できるため、JavaScriptを使わずネットワーク図のような複雑なGUIを作ることができる。

    ※2024-06-26現在、Chrome125、Edge125で利用可能

    <div class="box draggable" style="anchor-name: --one;   top: 0;     left: 0;">one</div>
    <div class="box draggable" style="anchor-name: --two;   top: 300px; left: 300px;">two</div>
    <div class="box draggable" style="anchor-name: --three; top: 150px; left: 600px;">three</div>
    
    <div class="line" style="--from: --one; --to: --two"></div>
    <div class="line" style="--from: --two; --to: --three"></div>
    .box {
      position: absolute;
      width: 10px;
      height: 10px;
      border: solid 4px;
      align-content: center;
      text-align: center;
    }
    .draggable {
      cursor: grab;
    }
    .draggable:active {
      cursor: grabbing;
    }
    
    /* 縦ライン */
    .line {
      anchor-name: --line;
      position: fixed;
      /* 中央に縦線を引く */
      background: linear-gradient(black, black) no-repeat center/2px 100%;
    
      /* ノードの位置によりアンカーポジションを反転する */
      position-try-options: flip-block, flip-inline, flip-block flip-inline;
      
      top: anchor(var(--from) center);
      left: anchor(var(--from) center);
      bottom: anchor(var(--to) center);
      right: anchor(var(--to) center);
    }
    
    /* 横ライン */
    .line::before,
    .line::after {
      position: fixed;
      display: block;
      content: '';
      background: black;
      height: 2px;
      position-try-options: inherit;
    }
    .line::before {
      bottom: anchor(var(--from) center);
      left: anchor(var(--from) right);
      right: anchor(--line center);
    }
    .line::after {
      bottom: anchor(var(--to) center);
      right: anchor(var(--to) left);
      left: anchor(--line center);
    }

    デモ

    See the Pen CSS Anchor Positioning by ダーシノ (@bcrikko) on CodePen.

    追記: 2024-09-20