javascripthtmldomcss-grid

How to make the grid in a fixed size even when the values changed?


I am creating etch-a-sketch. Currently, i figured out how to create a grid width user input values. But when the values changes the grid size changes. I want to make the width of the grid stays same whenever cell value changes. What should i do for that. I tried adjusting grid template rows and columns. It didn't work

Thank you

Here's my code

.grid{
    padding: 10px;
    display: inline-grid;
    justify-content: center;
    border: 1px solid black;
    gap: 1px;
}

.button-div{
    padding: 10px;
    display: flex;
    justify-content: center;
}
const container = document.getElementById('container');



//div for buttons
const buttonDiv = document.createElement('div');
buttonDiv.classList.add('button-div');
container.appendChild(buttonDiv);

//A button to reset Everything
const resetButton = document.createElement('button');
resetButton.textContent = 'Reset';
buttonDiv.appendChild(resetButton);

//grid in a seperate div
const grid = document.createElement('div');
grid.classList.add('grid');
container.appendChild(grid);

//function to create grid
function makeGrid(value){
    let gridWidth = 200 / value;
    grid.style.gridTemplateColumns = `repeat(${value}, ${gridWidth}px)`;
    grid.style.gridTemplateRows = `repeat(${value}, ${gridWidth}px)`;
    for(let i = 0; i < value; i++){
        for(let j = 0; j < value; j++){
        const cell = document.createElement('div');
        cell.classList.add('cell');
        cell.addEventListener('mouseover', toBlack);
        grid.appendChild(cell);
        }
    }
}


//to change the cell color to black on mouseover
function toBlack(e){
    e.target.style.backgroundColor = 'black';
}

function resetGrid(){
    const value = prompt('Input a number of Squares');
    grid.innerHTML = '';
    makeGrid(value);
}

resetButton.addEventListener('click',resetGrid);

window.onload = () => {makeGrid(16)};

Solution

  • I copy + pasted the code in your question to create a jsfiddle: https://jsfiddle.net/k8ebmqd4/

    What you've created so far is a fixed size .grid, where the number and size of the inner div.cell vary depending on the user input. Understanding your question correctly, this is not what you want. The div.cell should always stay 12.5x12.5 (that's what I see onload of the fiddle). If that's the case, just change this line:
    let gridWidth = 200 / value;
    to:
    let gridWidth = 12.5;
    And now the .grid sizes depending on the number of cells in it.

    Solution in according to comments below: remove the gap style from .grid and add a border to .cell: .cell{border:1px solid #FFFFFF;}. Please see: https://jsfiddle.net/t5akxof2/