Issue
I'm trying to create a 16x16 grid with flexbox. I have set the width property of every 17th element to 100% and flex-wrap
to wrap
to achieve this. However, for some reason, my code doesn't work. I don't get the 16x16 grid on my page. How can I solve this?
const cdiv = document.querySelector('.container');
// Add 16 divs
for (let i = 1; i < 257; i++) {
const div = document.createElement('div');
div.style.cssText = "border: 1px solid black; height: 25px; width: 25px";
cdiv.appendChild(div);
}
* {
box-sizing: border-box;
}
.container {
display: flex;
flex-wrap: wrap;
}
.container>div:nth-child((16n + 1)) {
width: 100% !important;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Etch-a-Sketch</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container"></div>
<script src="script.js"></script>
</body>
</html>
Solution
You have a typo in your nth child (extra brackets) - if you remove this and then unstyle, your 17th divs, you should get your grid:
const cdiv = document.querySelector('.container');
// Add 16 divs
for (let i = 1; i < 257; i++) {
const div = document.createElement('div');
cdiv.appendChild(div);
}
* {
box-sizing: border-box;
}
.container {
display: flex;
flex-wrap: wrap;
}
.container>div {
border: 1px solid black;
height: 25px;
width: 25px;
}
.container>div:nth-child(16n + 1) {
width: 100%;
border: 0;
height: 0;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Etch-a-Sketch</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container"></div>
<script src="script.js"></script>
</body>
</html>
You could just make the js do it for you depending on an input:
function createBoxes(numberPerRow) {
const cdiv = document.querySelector('.container');
const total = (numberPerRow * numberPerRow) + numberPerRow;
const mod = numberPerRow + 1;
for (let i = 1; i < total; i++) {
const div = document.createElement('div');
if (i % mod === 0) {
div.style.cssText = "border: 0; height: 0; width: 100%";
} else {
div.style.cssText = "border: 1px solid black; height: 25px; width: 25px";
}
cdiv.appendChild(div);
}
}
createBoxes(16);
* {
box-sizing: border-box;
}
.container {
display: flex;
flex-wrap: wrap;
}
<div class="container"></div>
Answered By - Pete
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.