By setting the gap: 0px
property in the flex-box container, I successfully made it fit within the container.
To ensure that each square fits perfectly within the container, I utilized the CSS Object Model to calculate and adjust their dimensions accordingly.
There are numerous methods to achieve this task, and this was just one of them.
class XSquare extends HTMLElement {
constructor() {
super();
// this.style.backgroundColor = 'white';
this.addEventListener('mouseenter', () => this.style.backgroundColor = 'black');
}
}
customElements.define('x-square', XSquare);
function createGrid(size) {
const container = document.getElementById('container');
container.innerHTML = ''; // Clear previous grid
container.style.padding = 0 + 'px';
container.style.margin = 0 + 'px';
container.style.width = 100 + '%';
container.style.height = 100 + '%';
container.style.gridTemplateColumns = `repeat(${size}, 1fr)`;
var containerWidth = container.attributeStyleMap.get("width").value;
var containerHeight = container.attributeStyleMap.get("height").value;
var sqSize = CSS.percent(Math.floor(Math.min(containerWidth / size, containerHeight / size)));
container.style.height = sqSize * size;
container.style.width = sqSize * size;
for (let i = 0; i < size * size; i++) {
const square = document.createElement('x-square');
square.style.maxWidth = sqSize
square.style.maxHeight = sqSize
square.style.minWidth = sqSize
square.style.minHeight = sqSize
container.appendChild(square);
}
}
document.getElementById('resize').addEventListener('click', () => {
const newSize = prompt('Enter new grid size (max 100)', 16);
if (newSize !== null && newSize <= 100) {
createGrid(newSize);
}
});
createGrid(16); // Initial grid creation
#container {
display: flex;
flex-wrap: wrap;
flex: 0 0 0 0;
width: 101%;
/* Fixed width for the container */
height: 99%;
margin: 0px;
padding: 0px;
border: 2px solid black;
// make gap between items 0px
gap: 0px
}
x-square {
aspect-ratio: 1;
/* Ensures squares remain square */
border: 1px solid black;
transition: background-color 0.3s;
/* Smooth color transition */
box-sizing: border-box;
max-width: 20px;
max-height: 20px;
margin: 0px;
padding: 0px;
}
x-square:hover {
background-color: black;
/* Color change on hover */
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Dynamic Etch-A-Sketch</title>
</head>
<body>
<button id="resize">Resize Grid</button>
<div id="container"></div>
</body>
</html>
You could also dynamically create the canvas using JavaScript by utilizing document.createElement("canvas") at the beginning.