Skip to content Skip to sidebar Skip to footer

Create Dynamic Equal Sized Small Squares Grid In Fixed Size Big Square

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

Solution 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 ofdocument.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: 010px10px0;
}

.grid>div {
  background: #333;
}
<divclass="grid"><div></div></div><divclass="grid"><div></div><div></div><div></div></div><divclass="grid"><div></div><div></div><div></div><div></div><div></div></div><divclass="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>

Post a Comment for "Create Dynamic Equal Sized Small Squares Grid In Fixed Size Big Square"