数とインデックスに基づいて兄弟要素のスタイルを設定する

これまで、リスト内の各兄弟に一意のスタイルを適用するには、複雑な :nth-child ループや JavaScript を使用してインライン スタイルを挿入する必要がありました。最新の CSS には、これらの計算をスタイルシートで直接実行するための sibling-index() と sibling-count() が用意されています。これにより、要素の追加や削除に応じて自動的に適応する動的なレイアウトとカラーシステムを実現できます。

ダイナミック カラー システム

子要素ごとに一意の色相または明度の値を計算することで、兄弟要素のグループ全体にカラースペクトルを作成できます。これにより、アイテムの数に関係なく、一貫したグラデーション効果が得られます。

.swatch {
  /* Calculate hue by dividing the full 360deg circle by total siblings */
  /* and multiplying by the current element's 1-based index */
  background-color: hsl(
    calc(360deg / sibling-count() * sibling-index()),
    70%,
    50%
  );
}

対称的なレイアウトとファン効果

対称的な効果(「扇形」やアイテムの中央揃えなど)を作成するには、合計数を使用してリストの中間点を見つけます。

.card {
  /* Find the center index (e.g., 3 if there are 5 siblings) */
  --center: calc((sibling-count() + 1) / 2);

  /* Rotate items away from the center: negative for left, positive for right */
  /* center element gets 0deg rotation */
  transform: rotate(calc(10deg * (sibling-index() - var(--center))));
}

円形および複雑な位置

これらの関数を CSS の三角関数(sin()、cos())と組み合わせることで、手動で座標を指定することなく、要素を完全な円に配置できます。

.orb {
  /* Calculate the angle for this item's position on a 360deg circle */
  --angle: calc(360deg / sibling-count() * sibling-index());
  --radius: 150px;

  /* Set the pre-transformed position for all items to be centered */
  position: absolute;
  place-self: center;


  /* Position each element around the parent center */
  transform: translate(
    calc(cos(var(--angle)) * var(--radius)),
    calc(sin(var(--angle)) * var(--radius))
  );
}

代替戦略

sibling-index() と sibling-count() がサポートされていない場合は、JavaScript を介して CSS カスタム プロパティを挿入することで、フォールバックを提供します。必須: CSS.supports() で機能検出を使用して、スクリプトが必要な場合にのみ実行されるようにします。

/* MANDATORY: Check for native support before applying fallback */
if (!CSS.supports('top: calc(sibling-index() * 1px)')) {
  const items = document.querySelectorAll('.item');
  items.forEach((item, index) => {
    /* MANDATORY: Injected index must be 1-based to match native function */
    item.style.setProperty('--sibling-index', index + 1);
    item.style.setProperty('--sibling-count', items.length);
  });
}

CSS では、これらの変数をベースとして使用し、@supports ブロック内のネイティブ関数でオーバーライドします。必須: 古いブラウザでも変数が有効になるように、ネイティブ関数のオーバーライドを @supports でラップする必要があります。

.item {
  /* 1. Set base values using variables (from JS fallback) */
  --index: var(--sibling-index);
  --count: var(--sibling-count);

  /* 2. Use the computed variables - replace this with your implementation-specific styles */
  background-color: hsl(calc(360deg / var(--count) * var(--index)), 70%, 50%);
}

@supports (top: calc(sibling-index() * 1px)) {
  .item {
    /* 3. Override with native functions ONLY if supported */
    --index: sibling-index();
    --count: sibling-count();
  }
}