const pageWidth = document.documentElement.scrollWidth;
const nRows = 10; const nColumns = 10;
const tableDiv = document.getElementById("tableDiv");
const rowHeight = Math.round(0.7*pageWidth/nRows);
tableDiv.style.width = 0.7*pageWidth + "px";
//tableDiv.style.height = 0.7*pageWidth + "px";
tableDiv.style.height = (rowHeight * nRows + 8 * (nRows-1)) + "px";
tableDiv.style.backgroundColor = "yellow";
// Dynamically generate a table of the specified dimensions
function constructTable(nR, nC) {
const tbl = document.createElement("table"); tbl.id = "test table";
var tRow; var tCell;
for (let r = 0; r < nR; r++) { // Use 'let,' not 'var,' or else all row/column numbers will be set to the final (maximum) values of r and c
tRow = document.createElement("tr");
tbl.appendChild(tRow);
for (let c = 0; c < nC; c++) {
tCell = document.createElement("td");
tCell.className = "testing";
tCell.innerHtml = c + 1;
tRow.appendChild(tCell);
}
}
return tbl;
}
function showTable(t) {
tableDiv.innerHTML = "";
tableDiv.appendChild(t);
const dynamicSizeCells = document.getElementsByClassName("testing");
for (var i = 0; i < dynamicSizeCells.length; i++) {
dynamicSizeCells[i].style.width = 0.7*pageWidth/nColumns + "px";
dynamicSizeCells[i].style.height = rowHeight + "px";
dynamicSizeCells[i].style.backgroundColor = "green";
}
console.warn("Div width is " + tableDiv.style.width + ", div height is " + tableDiv.style.height + "; cell width is " + dynamicSizeCells[0].style.width + ", cell height is " + dynamicSizeCells[0].style.height);
}
const theTable = constructTable(nRows, nColumns);
showTable(theTable);
body {
background-color: darkblue;
overflow-x: hidden;
}
#tableDiv {
margin-left: 15%;
margin-top: 5%;
}
.testing {
background-color: "green";
}
<div id="tableDiv"></div>
Your issue is "not consider row-space of tr elements". And, px value should be integer value. So, I'd modified some to calc correct height of div and row height. I hope this can be helped you. Regards.