CSS layout to distribute images on rows depending on images width?

Go To StackoverFlow.com


I have a list of div with each div having a image inside. The width of the images is not known before loading the page. I have a container div with width 960px. How can i arrange the images in rows with each row having as much images as the row width permits? So for example if i have 4 images (300px, 400px, 200px, 250px) i would need to have first 3 of them on a row and the 4-th one on second row as having all 4 of them in a single row will get a width larger then 960. And on each row the images should be centered.

I've tried all i could think of using css, and did not found a way that works.

Any ideea?

2012-04-04 21:04
by daniels
ur trials - can you provide a demo link?.. jsfiddle? - Vivek Chandra 2012-04-04 21:14


Something like THIS?

Ok, I worked with simply divs, because I didn't want to search for images but the main pont is: the elements which need to be both aligned and fitted, make them inline-block. Inline to be made multiline, box to be able to set both width and height. After that, you only need to set on the parent: text-align: center

EDIT Oups, I've put spaces between the divs (like real space characters) and they appear as spaces between the divs, since they are inline. make sure not tu put any whitespace between the containers, like THIS

2012-04-04 21:15
by Máthé Endre-Botond
Awesome. Thank you - daniels 2012-04-04 21:52


If you lose the containers, you don't even need to use inline-block.


However, since this is a list of images, you probably should use inline-block on the li elements of an unordered list.

2012-04-04 21:25
by Bryan Downing