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:
grid.children.length
- counts children ofgrid
div.Math.sqrt(grid.children.length)
- returns the square root of a children length.Math.ceil(Math.sqrt(grid.children.length))
- rounds a number up to the next largest integer. So we get ours column and rows number.--cols
- set CSS variable to ourgrid
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"