Cómo aplicar diseño a elementos hermanos según el recuento y el índice

Históricamente, aplicar estilos únicos a cada elemento hermano de una lista requería bucles :nth-child complejos o JavaScript para insertar estilos intercalados. El CSS moderno proporciona sibling-index() y sibling-count() para realizar estos cálculos directamente en tu hoja de estilo, lo que permite diseños dinámicos y sistemas de colores que se adaptan automáticamente a medida que se agregan o quitan elementos.

Sistemas de colores dinámicos

Puedes crear un espectro de colores en un grupo de elementos hermanos calculando un valor único de tono o luminosidad para cada elemento secundario. Esto garantiza un efecto de gradiente coherente, independientemente de la cantidad de elementos.

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

Diseño simétrico y efectos de abanico

Para crear efectos simétricos (como un "abanico" o elementos centrados), usa el recuento total para encontrar el punto medio de la lista.

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

Posicionamiento circular y complejo

Si combinas estas funciones con la trigonometría de CSS (sin(), cos()), puedes colocar elementos en un círculo perfecto sin coordenadas manuales.

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

Estrategias de resguardo

Si no se admiten sibling-index() ni sibling-count(), proporciona un resguardo insertando propiedades personalizadas de CSS a través de JavaScript. OBLIGATORIO: Usa la detección de funciones con CSS.supports() para asegurarte de que la secuencia de comandos solo se ejecute cuando sea necesario.

/* 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);
  });
}

En tu CSS, usa estas variables como base y anúlalas con funciones nativas dentro de un bloque @supports. OBLIGATORIO: DEBES unir las anulaciones de funciones nativas en @supports para garantizar que las variables sigan siendo válidas en los navegadores más antiguos.

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