DEV Community

sa3i0l
sa3i0l

Posted on

Grid layout with adaptive squares

Grid layout with adaptive squares, depending, on how much squares you want it to have.

Explanation:

In index.html we add <div> which is grid layout.
With default values as 16 rows and columns.
And it have fixed width and height, and all squares inside (how much you want to have), need to be made inside that space.

<div id="grid"></div>

<style>
#grid { display: grid; grid-template-columns: repeat(16, 1fr); grid-template-rows: repeat(16,1fr); width: 300px; height: 300px;}</style>
Enter fullscreen mode Exit fullscreen mode
var x = 30;  // with this, we determine how much squares we want to have

// to get <div> element which is grid layout (parent), so we add (append) all children to this
var grid = document.getElementById("grid");


Enter fullscreen mode Exit fullscreen mode
  • Here we use , to execute ${x} , which means, to have that much squares. this is crucial to get all squares to shrink evenly !!! (after we added all childs to parent, they won't shrink without this !! )

// here we use ` ` , to execute ${x} , which means, to have that much squares. this is crucial to get all squares to shrink evenly !!! 
grid.style.gridTemplateColumns = `repeat(${x}, 1fr)`;
grid.style.gridTemplateRows = `repeat(${x}, 1fr)`;
Enter fullscreen mode Exit fullscreen mode
  • And this is used, to make that much squares, equally across, append it to grid layout (parent), and have it's border
// and this is used, to make that much squares, equally across
// append it to grid layout (parent)
// and have it's border 
for (var i = 0; i < x * x; i++ ){

    var cell = document.createElement("div");

    cell.style.border = "0.1px solid black";
    cell.style.borderCollapse = "collapse";

    grid.appendChild(cell);
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)