So I was working on a small project and I was able to complete it, too. At the end of the project, I noticed that the code shouldn't work but it was working:
let size = 15; //fornow
const con = document.querySelector("#container");
for (i = 0; i < size; i++) {
for (j = 0; j < size; j++) {
let box = document.createElement("div");
box.style.cssText = `grid-area: ${i + 1}/${j + 1}/${i + 2}/${j + 2}`;
box.classList.add("tile");
con.appendChild(box);
}
}
#container {
height: 50vh;
width: 50vh;
border: 4px rgb(216, 216, 216) solid;
display: grid;
margin: 50px auto;
}
.tile {
border: 1px rgb(0, 0, 0) solid;
background-color: white;
}
<div id='container'></div>
A perfect square grid gets created when the size variable is given a value with all the divs arranged in rows and columns. This thing I didn't understand is that I just wrote a container to be display: grid
and didn't even define any row-column or template or even any grid property. Even grid: 'something'
is missing too.
How come my code works and all the child elements get perfectly arranged by just using grid area property where the max area isn't even defined?
I tried to search if there is any by default grid property, but even it requires you to write something starting with "grid".
How come my code works and all the child elements get perfectly arranged by just using grid area property where the max area isn't even defined?
You don't need to define any rows or columns ("tracks") on the container.
In the absence of author-defined ("explicit") tracks, the grid algorithm creates its own ("implicit") tracks to accommodate grid areas.
With your script, you are creating implicit grid lines.
As you can see in the CSS, the grid-area
property is defining row and column lines. Because these lines don't match to any explicit tracks, implicit tracks are created.
From the spec:
The three properties
grid-template-rows
,grid-template-columns
, andgrid-template-areas
together define the explicit grid of a grid container.
But these properties don't exist in the code. So the JS ends up creating implicit lines.
The
grid-template-rows
,grid-template-columns
, andgrid-template-areas
properties define a fixed number of tracks that form the explicit grid. When grid items are positioned outside of these bounds, the grid container generates implicit grid tracks by adding implicit grid lines to the grid.
The "perfect square" shape of the container is a result of its defined size (50vh
x 50vh
).
#container {
height: 50vh;
width: 50vh;
border: 4px rgb(216, 216, 216) solid;
display: grid;
margin: 50px auto;
}