Search code examples
javascripthtmlcssuser-interfacecss-grid

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.

enter image description here


Solution

  • 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>