Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

110
Views
Html / CSS / JavaScript Automatic format divs with a ratio into another div

I want to make an interface with a container where the user choose a number of squares to showing in. The squares have to use the maximum of space, with a minimum lost. So, the width of a square have must to be calculated from the container's width and height.

Starting with this problem, I quickly arrived at 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
}

JSFiddle

In theory this works, but this function does not take into account the wasted space of the container. In other words, it gives the side of one of the squares, if we want to use the whole container. But we only want to use the maximum portion of the container to display them, not the whole thing.

So I started from the principle that I had to find a way to recover the excess 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);
}

JSFiddle

That's the best result I have. But that's not perfect. Some squares can exit the container.

I have made some other experiment, but nothing to show here. I have made some tests with css but I didn't get there either.

If someone has an idea, I'm interested!

P.S : My English is not bad at all, but I have to learn more ! So, don't be shy to claim some details if needed.

Thanks !

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!