2

I'm writing a a layout in CSS and HTML where I want the expected layout to be rendered out from left to right, top to bottom like this:

wanted layout

Each box has different height but the same width. I don't know how many boxes there are, it can vary from 2 to 20. I've tried float: left, but then you will get empty space depending on the size of the boxes. I've also tried column in CSS3, but It behaves very randomly, both on browser type, number of boxes and the size of the boxes. Does anyone know a smart trick to make it look like this, and preferably without the use of Javascript.

Numm3n
  • 1,021
  • 2
  • 9
  • 26
  • have you tried using `clear:both` after each element so that the element does not lose its height after your use `float:left` on it? – Fahad Sohail Dec 02 '16 at 12:24
  • Yes, unfortunately you'll still get a lot of spaces between the boxes. – Numm3n Dec 02 '16 at 12:32
  • 1
    please google "masonry layout css" or better "masonry layout flexbox". It would be really helpful. – Vadim Ovchinnikov Dec 02 '16 at 12:33
  • @VadimOvchinnikov I still havent found a good solution. F.ex http://w3bits.com/demo/css-masonry/ still gives you "holes" on the layout. Look at the bottom row in Google Chrome – Numm3n Dec 02 '16 at 12:44
  • No pure CSS solution exists: neither floats nor flexbox and grid layout can achieve that with unknown heights of items. [Top to bottom, left to right is possible](http://codepen.io/olivier-c/pen/KNvVMq) though I didn't test with more complicated content (containing floats by example, then BFC to the rescue) – FelipeAls Dec 02 '16 at 13:22

2 Answers2

1

Masonry does this: http://masonry.desandro.com/ - That's with JS though

Njaal Gjerde
  • 653
  • 1
  • 6
  • 14
0

You could achieve this with pure CSS. Use the column-width property and for the spacing a combination of column-gap and padding

HTML

<section>
  <img src="path" />
  <img src="path" />
  <img src="path" />
</section>

CSS

section{
  column-width: 300px;
  column-gap: 5px;
  padding: 5px;
}

section img{
  width: 100%; 
}

Demo

Pen

SvenL
  • 1,904
  • 8
  • 10