Create dynamic equal sized small squares grid in fixed size big square

老子叫甜甜 提交于 2021-02-04 21:07:34

问题


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


回答1:


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

JS explanation:

  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.

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>


来源:https://stackoverflow.com/questions/62371077/create-dynamic-equal-sized-small-squares-grid-in-fixed-size-big-square

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!