Matt
Matt

Reputation: 6963

Algorithm for fitting different sized rectangles in a larger rectangle

I need an algorithm to calculate best fit for rectangles in a larger rectangle.. and the larger rectangle changes size dynamically. More details:

I am using the Code52 Metro UI project: http://code52.org/metro.css/

I am using only ONE tile row and all the tiles have "float:left" defined. This works beautifully when all the tiles are of the same size.. a user can resize the browser to any width and the tiles just "drop down" under each other. Now the problem comes in when I want different tile sizes. This breaks everything and is obviously why people generally design metro UIs as fixed width. Well, I need to go with a fluid layout if possible. Tile sizes are pre-defined as follows:

Single: 130px x 130px
Double Horizontal: 130px x 280px
Double Vertical: 280px x 130px
and Double Both: 280px x 280px

Container is fluid, so width/height changes dynamically.

What I need is an algorithm to make a best-fit for the tiles.. so any empty spaces will only be at the bottom-right corner and not mixed in with the tiles. Any math genius here with an idea?

Upvotes: 2

Views: 3137

Answers (1)

Markus Jarderot
Markus Jarderot

Reputation: 89231

You might want to look at jQuery Masonary. It is designed to do this for any size of tiles. The example on the front page even has exactly what you are trying to do.

Upvotes: 1

Related Questions