在固定大小的大正方形中创建动态等大小的小正方形网格 [英] Create dynamic equal sized small squares grid in fixed size big square

查看:66
本文介绍了在固定大小的大正方形中创建动态等大小的小正方形网格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在固定的大正方形内创建动态等大小的正方形?大小应根据平方数来确定.

How can I be able to create dynamic equal-sized squares inside a fixed big square? size should be according to number of squares.

推荐答案

这将是最通用的解决方案.根据子元素的总和,使用CSS grid 白色的可数列和行.

This will be the most universal solution. Using CSS grid whit countable column and rows, according to the sum of children element.

JS说明:

  1. grid.children.length -计算 grid div的子级.
  2. Math.sqrt(grid.children.length)-返回子项长度的平方根.
  3. Math.ceil(Math.sqrt(grid.children.length))-将数字四舍五入到下一个最大整数.这样我们就得到了我们的列数和行数.
  4. -cols -将CSS变量设置为我们的 grid 元素.
  1. grid.children.length - counts children of grid div.
  2. Math.sqrt(grid.children.length) - returns the square root of a children length.
  3. Math.ceil(Math.sqrt(grid.children.length)) - rounds a number up to the next largest integer. So we get ours column and rows number.
  4. --cols - set CSS variable to our grid elemetn.

此JavaScript可与任意数量的 grid 块一起使用.

This JavaScript works with any number of grid block.

for (const grid of document.querySelectorAll('.grid')) {
  grid.style.setProperty('--cols', Math.ceil(Math.sqrt(grid.children.length)));
}

.grid {
  --cols: 1;
  width: 100px;
  height: 100px;
  display: inline-grid;
  grid-template-columns: repeat(var(--cols), 1fr);
  grid-template-rows: repeat(var(--cols), 1fr);
  column-gap: 2px;
  row-gap: 2px;
  background: #eee;
  vertical-align: top;
  margin: 0 10px 10px 0;
}

.grid>div {
  background: #333;
}

<div class="grid">
  <div></div>
</div>
<div class="grid">
  <div></div>
  <div></div>
  <div></div>
</div>
<div class="grid">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>
<div class="grid">
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

这篇关于在固定大小的大正方形中创建动态等大小的小正方形网格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆