I am able to create the grid using a for loop. I then prompt for the number of rows and number of columns as the x and y values, respectively. I am having trouble understanding how one would go about creating divs that resize to fit the size of a container - with the container never exceeding the size of the page(?). Any suggestions?
let x = parseInt(prompt("how many rows?"));
let y = parseInt(prompt("how many columns?"));
const reset = document.getElementById("reset");
reset.addEventListener("click", function() {
location.reload();
});
const container = document.getElementById("container");
const rows = document.getElementsByClassName("gridRow");
const cells = document.getElementsByClassName("cell");
function makeGrid() {
makeRows(x);
makeCols(y);
}
function makeRows(rowNum) {
for (i = 0; i < rowNum; i++) {
let row = document.createElement("div");
container.appendChild(row).className = "gridRow";
}
}
function makeCols(colNum) {
for (i = 0; i < rows.length; i++) {
for (j = 0; j < colNum; j++) {
let col = document.createElement("div");
rows[j].appendChild(col).className = "cell";
}
}
}
makeGrid();
:root {
display: flex;
justify-content: center;
align-items: center;
}
.cell {
border: 1px solid gray;
min-width: 30px;
min-height: 30px;
margin: 4px;
display: inline-flex;
}
.cell:hover {
cursor: pointer;
background-color: antiquewhite;
}
.cell:active {
background-color: antiquewhite;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="script.js" defer></script>
<link rel="stylesheet" href="style.css" />
<title>Etch-A-Sketch</title>
</head>
<body>
<button id="reset" class="reset">RESET</button>
<div id="container"></div>
</div>
</body>
</html>
I'm not sure I understand the whole question, but here is an example that will share the width and height of the grid itself.
The key is to use the flex layout and fix the initial grid size using vw and vh units.
I have simplified the code to focus on a minimal example.
function makeCells(rows, columns) {
let grid = document.getElementById("grid");
for (i = 0; i < rows; i++) {
let row = document.createElement("div");
row.className = "row";
for (j = 0; j < columns; j++) {
let column = document.createElement("div");
column.className = "cell";
row.appendChild(column);
}
grid.appendChild(row);
}
}
makeCells(4, 3);
.grid {
display: flex;
flex-direction: column;
align-items: stretch;
border: 1px solid red;
width: 50vw; /* 50% of viewport width */
height: 50vh; /* 50% of viewport height */
}
.row {
display: flex;
flex-direction: row;
align-items: stretch;
border: 1px solid blue;
height: 100%;
}
.cell {
border: 1px solid green;
height: 100%;
width: 100%;
}
<div id="grid" class="grid"></div>