Ask coding questions

← Back to all posts
How to change the number of squares in a div while retaining the same grid size?
lblare123 (0)

I am trying to have a button that prompts the user to change the number of squares of a 16x16 sketchpad grid to their choice of squares while having the grid occupy the same amount of space as before. So, if the user enters 10 or 100, the grid squares will rearrange from 16x16 to 10x10 to 100x100, respectfully, without changing size altogether.

However, when I enter a number into the prompt, the number of squares in a row changes accordingly while the number of squares in a column increases. The overall size of the grid also changes. Maybe there are squares are being added to the grid on repeat more than expected? Or I need to erase the grid altogether?

I tried using justify-content: stretch but I seem to have the same problem.

Thank you in advance for your time and help.

InvisibleOne (2979)

Well... I would do something like this
First calculate how wide you want the max to be, maybe 1000px for the sake of this argument. Then you need to calculate how wide the squares can be to fit into that size.

maxSquareWidth = 1000 / numSquares

Then set all the squares to that width and height.

squares = document.getElementsByClassName('classname')
for (var i=0; I<squares.length; I++) {
  squares[i].style.width = maxSquareWidth;
  squares[i].style.height = maxSquareWidth;

I haven't checked if that works exactly but I think it should.

xxpertHacker (930)

@InvisibleOne They're using CSS flex box, not JS :/