You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用CSS实现按元素数量自动均匀分布的类圆形布局

实现类圆形列表排布的两种简便方案

方案1:自适应网格类圆形排布(元素整体轮廓近似圆形,纯CSS无JS)

适合不需要严格沿圆周分布,只要整体外轮廓接近圆形的场景,自动适配元素数量:

/* 容器样式 */
.circle-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(60px, 1fr));
  gap: 16px;
  max-width: 600px;
  aspect-ratio: 1 / 1;
  margin: 0 auto;
  align-items: center;
  justify-items: center;
  padding: 20px;
}
/* 列表元素样式 */
.circle-item {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  background: #2196F3;
}

这个方案会根据容器宽度和元素尺寸自动调整每行的元素数量,配合正方形的容器比例,最终整体呈现近似圆形的排布效果。

方案2:圆周均匀排布(严格沿圆形分布,适配任意元素数量)

需要元素严格均匀分布在圆周上时,用这个方案,只需要加一行可选JS就能完全自动适配元素数量:

<!-- 结构示例 -->
<div class="circle-wrapper">
  <div class="circle-item"></div>
  <div class="circle-item"></div>
  <!-- 支持任意数量的子元素 -->
</div>
.circle-wrapper {
  position: relative;
  /* 圆周直径 */
  width: 300px;
  height: 300px;
  /* 总元素数量变量,可通过JS自动赋值 */
  --n: 8; 
}
.circle-item {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 40px;
  height: 40px;
  /* 偏移量为元素宽度的一半,保证圆心对齐圆周 */
  margin: -20px 0 0 -20px;
  border-radius: 50%;
  background: #4CAF50;
  /* 核心计算:自动计算当前元素的角度,沿圆周分布 */
  transform: rotate(calc(360deg / var(--n) * (var(--i) - 1))) translate(130px) rotate(calc(-360deg / var(--n) * (var(--i) - 1)));
}
/* 自动给元素设置序号变量,可按需扩展到足够多的数量 */
.circle-item:nth-child(1) { --i: 1; }
.circle-item:nth-child(2) { --i: 2; }
.circle-item:nth-child(3) { --i: 3; }
.circle-item:nth-child(4) { --i: 4; }
.circle-item:nth-child(5) { --i: 5; }
.circle-item:nth-child(6) { --i: 6; }
.circle-item:nth-child(7) { --i: 7; }
.circle-item:nth-child(8) { --i: 8; }

如果需要完全自动适配元素数量,不用手动设置--n和扩展nth-child规则,加一段JS即可:

const wrapper = document.querySelector('.circle-wrapper')
const items = wrapper.querySelectorAll('.circle-item')
wrapper.style.setProperty('--n', items.length)
// 动态给元素设置--i变量
items.forEach((item, index) => item.style.setProperty('--i', index + 1))

内容的提问来源于stack exchange,提问作者noosh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.09 10:39:02