如何让多个div元素围绕指定中心div实现环绕排列(HTML/CSS/JS)
实现圆形div环绕中心蓝色块排列的解决方案
需求说明
当前圆形div(MinuteBall)位于蓝色大矩形下方,需要调整为环绕中心蓝色矩形排列,同时保持索引从左到右、从上到下递增的顺序,仅适配Firefox浏览器与2560x1440屏幕。
修改后的代码
HTML
结构保持不变,确保容器层级正确:
<html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="style.css"> <script defer src="code.js"></script> <title>1440 Minutes wallpaper</title> </head> <body> <div id='flexbox'> <div id="info">big block</div> <div id="balls"></div> </div> </body> </html>
CSS
改用Grid布局实现整体排列,调整容器定位与间距:
body { margin: 0; } #flexbox { width: 2560px; height: 1440px; position: relative; /* 让蓝色块的绝对定位基于此容器 */ } #balls { width: 100%; height: 100%; display: grid; /* 每行60列,每列宽度=球宽40px+间距2px */ grid-template-columns: repeat(60, 42px); /* 共24行,每行高度=球高40px+间距2px */ grid-template-rows: repeat(24, 42px); gap: 2px; /* 统一设置球之间的间距,替代margin */ } #info { width: 560px; height: 440px; font-size: 50px; color: white; background-color: rgba(0,0,255,0.5); position: absolute; top: 500px; left: 1000px; z-index: 1; /* 确保蓝色块显示在圆形div上方 */ } .MinuteBall { background-color: gray; width: 40px; height: 40px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-size: 12px; /* 让数字适配圆形大小 */ }
JavaScript
通过行列遍历跳过蓝色块区域,按顺序生成圆形div:
document.body.onload = InitiateWallpaper; function InitiateWallpaper() { const ballsContainer = document.getElementById("balls"); const totalBalls = 1440; let currentIndex = 0; // 计算蓝色块占据的网格行列范围(基于2560x1440与42px的网格单元) const infoStartCol = 23; // 左偏移1000px对应的起始列索引 const infoEndCol = 36; // 蓝色块宽度560px对应的结束列索引 const infoStartRow = 11; // 上偏移500px对应的起始行索引 const infoEndRow = 21; // 蓝色块高度440px对应的结束行索引 // 按行优先遍历所有网格位置 for (let row = 0; row < 24; row++) { for (let col = 0; col < 60; col++) { // 跳过蓝色块覆盖的区域 if (row >= infoStartRow && row <= infoEndRow && col >= infoStartCol && col <= infoEndCol) { continue; } // 达到总数则停止生成 if (currentIndex >= totalBalls) break; const ball = document.createElement("div"); ball.classList.add("MinuteBall"); ball.textContent = currentIndex; ballsContainer.appendChild(ball); currentIndex++; } if (currentIndex >= totalBalls) break; } }
关键修改说明
- 布局切换:将
#balls从Flex布局改为Grid布局,方便精确控制每个圆形div的位置,同时实现行列对齐。 - 区域跳过:通过计算蓝色块在网格中的行列范围,遍历生成时跳过该区域,自然形成环绕效果。
- 层级控制:给蓝色块设置
z-index:1,确保它始终显示在圆形div上方,避免被遮挡。 - 间距优化:用Grid的
gap属性替代margin,避免间距叠加问题,布局更稳定。
内容的提问来源于stack exchange,提问作者ustor1k3
相关产品推荐
相关产品推荐

