mxn divs in div js
·
1 min read
·
edit
result
code
<div id="container">
</div>
<script>
function createGrid(m, n, s) {
const rowsRep = "(" + m + ", " + s + ")";
const colsRep = "(" + n + ", " + s + ")";
const pDiv = document.createElement("div");
pDiv.style.display = "grid";
pDiv.style.gridTemplateColumns = "repeat" + colsRep;
pDiv.style.gridTemplateRows = "repeat" + rowsRep;
pDiv.style.gap = "4px";
for(let i = 0; i < m; i++) {
for(let j = 0; j < n; j++) {
const cDiv = document.createElement("div");
cDiv.style.width = s;
cDiv.style.height = s;
cDiv.style.background = "var(--bg)";
cDiv.style.border = "1px solid var(--muted-border)";
cDiv.style.borderRadius = "4px";
pDiv.append(cDiv);
}
}
return pDiv;
}
</script>
<script>
// get container element, set style
let cnt = document.getElementById("container");
cnt.style.marginTop = "1em";
// create grid element
let grid = createGrid(3, 4, "20px");
// append element to container
cnt.append(grid);
</script>
steps
- Open a plain text editor, e.g. vim, nano, Notepad++, VS Code.
- Copy and paste code given above.
- Save with new name, e.g.
jstu-10-mxn-divs-in-div.html. - View using an internet browser, e.g. Google Chrome, Mozilla Firefox, Apple Safari.
- Edit HTML file for further modification.
- Save the changes
- Refresh internet browser to see updated result.
- Repeat the previous three steps (5-7).
- Close the internet browser.
- Close the plain text editor.