Puedo crear la grilla usando un bucle for. Luego solicito el número de filas y el número de columnas como los valores x e y, respectivamente. Tengo problemas para entender cómo se haría para crear divs que cambien de tamaño para adaptarse al tamaño de un contenedor, sin que el contenedor exceda el tamaño de la página (?). ¿Alguna sugerencia?
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>No estoy seguro de entender toda la pregunta, pero aquí hay un ejemplo que compartirá el ancho y el alto de la cuadrícula.
La clave es usar el diseño flex y fijar el tamaño de cuadrícula inicial usando unidades vw y vh .
He simplificado el código para centrarme en un ejemplo mínimo.
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>