HTML / CSS / JavaScript automatic format divs with a ratio to another div

I want to create an interface with a container where the user selects several squares to display. Therefore, the width of a square must be calculated from the width and height of the container.

Starting with this issue, I quickly reached this function:

function calcSquareWidth(nbSquares = 1) { //items is the number of squares
  let width = $('#container').width();    //width of the container
  let height = $('#container').height();  //height of the container

  return Math.sqrt((width * height) / nbSquares); //width of a square
}

JS Fiddle

This works in theory, but this function does not take into account the lost space of the container. In other words, if we want to use the whole container, it turns into one of the squares. But we just want to use as much of the container as possible to show them, not the whole thing.

So I started with the principle that I have to find a way to recover the extra surface, then subtract it from the total surface of the container and apply my function.

function calcSquareWidth(nbSquares = 1) {
  let width = $('#container').width();    //width of the container
  let height = $('#container').height();  //height of the container
  let surface = width * height;  //surface of the container

  let x = Math.sqrt( surface / nbSquares); //side of a square use the whole container

  // To get the excess, I divide the container width and height by the side of a square and I get the integer part
  let eWidth = Math.floor(width / x) * x;    //width of the excess
  let eHeight = Math.floor(height / x) * x;  //height of the excess
  let eSurface = eWidth * eHeight;           //surface of the excess

  return x - (Math.sqrt(surface - eSurface) / nbSquares);
}

JS Fiddle

This is the best result I have. But it is not perfect. Some squares can come out of the container.

I’ve tried something else, but there’s nothing to show here. I did some tests with CSS but I didn’t get there.

I’m interested if anyone has an idea!

PS: My English is not bad at all, but I have to learn more! So, don’t be shy about claiming some details if needed.

Thanks !

Write a Comment