Finding a solution for distribution may be challenging. Perhaps there is a jQuery library that can assist with some aspects of it... I will investigate further. Despite the complexity, solving this problem is quite enjoyable.
Here is my current progress, although it is somewhat brief.
http://jsfiddle.net/twPQ7/2/
The section that calculates how many additional components need to be built is the tricky part. I am aiming to minimize the number of loops in this process:
var containerSize = getContainerSize();
var elementWidth = 0;
var elementHeight = 0;
// calculating width
while (elementWidth < containerSize.x)
{
var size = generateElement();
elementWidth += size.x;
elementHeight += size.y;
}
// adjusting height if necessary
while (elementHeight < containerSize.y)
{
var size = generateElement();
elementWidth += size.x;
elementHeight += size.y;
}
I have made some improvements. Please review the updated fiddle: http://jsfiddle.net/twPQ7/2/
// determining container size
var containerSize = getContainerSize();
var elementWidth = 0;
var elementHeight = 0;
// generating elements iteratively until reaching container width
while (elementWidth < containerSize.x)
{
var size = generateElement();
elementWidth += size.x;
// keeping track of the tallest element.
if (size.y > elementHeight) elementHeight = size.y;
}
// generating elements iteratively until reaching container height
while (elementHeight < containerSize.y)
{
var size = generateElement();
elementHeight += size.y;
}