Here is an algorithm that will use the entire width and all unused space will be at the bottom. This will not always give the largest possible squares, but it will behave in a consistent manner and should look nice.
Note that the while
loop should normally not go more than one or two iterations.
function CalcSize (){
var number = 23; // Example-Number
var width = jQuery('#container').width();
var height = jQuery('#container').height();
var area = height * width;
var elementArea = parseInt(area / number);
// Calculate side length if there is no "spill":
var sideLength = parseInt(Math.sqrt(elementArea));
// We now need to fit the squares. Let's reduce the square size
// so an integer number fits the width.
var numX = ceil(width/sideLength);
sideLength = width/numX;
while (numX <= number) {
// With a bit of luck, we are done.
if (floor(height/sideLength) * numX >= number) {
// They all fit! We are done!
return sideLength;
}
// They don't fit. Make room for one more square i each row.
numX++;
sideLength = width/numX;
}
// Still doesn't fit? The window must be very wide
// and low.
sideLength = height;
return sideLength;
}