Oskar Persson
Oskar Persson

Reputation: 6765

PHP: Dynamic image grid with different widths

On my site I have multiple images with the same height but with three different widths. And I want to display these in a nice grid. When an image is uploaded I check if the image should be wide or tall.

I then have three different sizes for images s, m & l

s for tall images and m & l for wide images.

These images are displayed in a table where a small (s) image takes up 1 spot, medium (m) takes up 2 spots and large (l) takes up 3 spots. And there are 3 spots per row.

If I have maybe 8 images (4 tall and 4 wide) I want it to look like this (w = white-space):

sss
ms
l
l
l

instead of

sss
sww
l
l
l
l

This means that the first 3 images are just small images. And since I need a medium image for the second row then I strech one of the wide images to take up 2 spots. Then there is a tall image beside that one and the last three rows are just three wide images, one on each row.

I hope I explained this well enough.

EDIT:

Or let's say I've got 4 images 2 tall and 2 wide (w = white-space):

Instead of displaying it like this

ssw
l
l

I want it to look like this:

sm (or ms)
sm (or ms)

How do I make this work?

Upvotes: 0

Views: 1458

Answers (1)

Korvin Szanto
Korvin Szanto

Reputation: 4511

There are several libraries for this, the easiest is jQuery Masonry.

You could achieve what you want with minimal code because it's only variable widths rather than variable widths and heights, but might as well use a library that already handles this rather than spend the time yourself.

Upvotes: 3

Related Questions