根据数量和索引设置同级元素的样式

过去,要为列表中的每个同级元素应用独特的样式,需要使用复杂的 :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();
  }
}