개수 및 색인을 기반으로 동위 요소 스타일 지정

이전에는 목록의 각 동위 요소에 고유한 스타일을 적용하려면 복잡한 :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로 래핑해야 합니다(MUST).

.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();
  }
}